неділя, 11 грудня 2011 р.

Objective-c та @"Перший об"єкт..."

Давно, я вже нічого не писав, в своєму блозі. Проте з'явилася вільна хвилинка і я вирішив, написати трошки коду аби зацікавленість не падал з дня в день. 
Перекладаючи назву Objective-C, стає, ясно практично кожній людині, яка хоч якось пересікалась з англійською мовою або просто з програмуванням, що мова об'єктно орієнтована. Тому прийшов час показати, як з себе виглядає, найпростіший об'єкт. 
Для роботи нам будуть необхідні 3 файли:
Person.h - інтерфейс
Person.m - реалізація
start.m - створення об'єкту.
Внизу описано простий клас, який в собі містить інформацію, про людину, яка закінчила школу. А саме ім'я, прізвище, місто, назва школи та рік народження.



Якщо ви все правильно зробите, то результат має бути таким:
Person.h

//Person.h 
#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    NSString * firstName;
    NSString * lastName;
    NSString * city;
    NSString * school;
    NSInteger  year;
}

@property (nonatomic, retain) NSString * firstName;
@property (nonatomic, retain) NSString * lastName;
@property (nonatomic, retain) NSString * city;
@property (nonatomic, retain) NSString * school;
@property (nonatomic) NSInteger year;

-(void) setFirstName:(NSString *) theName;
-(NSString *) firstName;

-(void) setCity:(NSString *) theName;
-(NSString *) city;

-(void) setSchool:(NSString *) theName;
-(NSString *) school;

-(void) setLastName:(NSString *) theName;
-(NSString *) lastName;

-(void) setYear:(NSInteger) theYear;
-(NSInteger) year;

@end

Person.m


// Person.m
#import <Foundation/Foundation.h>
#import "Person.h"

@implementation Person
   
-(void) setFirstName:(NSString *) theName
{
    firstName = theName;
}

-(NSString *) firstName
{
    return firstName;
}

-(void) setLastName:(NSString *) theName
{
    lastName = theName;   
}

-(NSString *) lastName
{
    return lastName ;
}

-(void) setYear:(NSInteger) theYear
{   
    year = theYear;
}
-(void) setCity:(NSString *) theName
{
    city = theName;
}
-(NSString *) city
{
    return city;
}

-(void) setSchool:(NSString *) theName
{
    school = theName;   
}
-(NSString *) school
{
    return school;
}
-(NSInteger) year
{
    return year;
}

-(NSString *) description
{
    NSString * result = nil;
    result = [NSString stringWithFormat:@"Person first name: %@\nLast name: %@\nCity:%@\nGraduated from school number:%@\nFrom: %i year.",firstName, lastName, city, school, year];
    return result;
}
   
@end


Start.m

#import <Foundation/Foundation.h>
#import "Person.m"

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   
    Person * student = [[Person alloc] init];
    [student setFirstName:@"Petryk"];
    [student setLastName:@"Piyatochkin"];
    [student setCity:@"Cheerkasy"];
    [student setSchool:@"#17"];
    [student setYear:1984];
    NSLog(@"Deal #1 \n%@",[student  description]);
   
    [student release];
    [pool drain];
   
    return (0);
}

А також, оновлений словник:


/*
v. 1. 0. 4
(~THE_DICTIONARY_OF_OBJECTIVE_C_WORDS~)
Example
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   
    [pool drain];
}

. /usr/share/GNUstep/Makefiles/GNUstep.sh

gcc `gnustep-config --objc-flags` -lgnustep-base <name file>.m -o <name .o file> ./<name file >  Example:  gcc `gnustep-config --objc-flags` -lgnustep-base hello.m -o hello
./hello

 gcc `gnustep-config --objc-flags` -lgnustep-base start.m -o hello



@interface @implementation @end @class @property @protocol @selector @synthesize @private @protected @public
void return BOOL YES NO new unsigned const volatile in out inout bycopy byref oneway self
#pragma
char short int long float double signed unsigned id  drain count description
alloc init initWith retain release autorealease nonatomic nil

stringWithFormat arrayWithObjects


NSArray
initWithArray: initWithArray:copyItems: initWithContentsOfFile: initWithContentsOfURL: initWithObjects: initWithObjects:count:
 indexOfObject:  indexOfObject:inRange: indexOfObjectIdenticalTo: indexOfObjectIdenticalTo:inRange: indexOfObjectPassingTest:
 indexOfObjectWithOptions:passingTest: indexOfObjectAtIndexes:options:passingTest: indexesOfObjectsPassingTest: indexesOfObjectsWithOptions:passingTest:
 indexesOfObjectsAtIndexes:options:passingTest: indexOfObject:inSortedRange:options:usingComparator:
componentsSeparatedByString:  componentsJoinedByString: 
 NSDictionary
 dictionary dictionaryWithContentsOfFile:  dictionaryWithContentsOfURL: dictionaryWithDictionary:  dictionaryWithObject:forKey: dictionaryWithObjects:forKeys:
 dictionaryWithObjects:forKeys:count:  dictionaryWithObjectsAndKeys:  initWithContentsOfFile: initWithContentsOfURL: initWithDictionary: initWithDictionary:copyItems:
 initWithObjects:forKeys: initWithObjects:forKeys:count: initWithObjectsAndKeys: objectForKey: getObjects:andKeys: valueForKey:
 NSNumber: (NSArray *)allKeys
 numberWithChar: numberWithInt: numberWithFloat: numberWithBool




 NSString
 string init initWithBytes:length:encoding: initWithBytesNoCopy:length:encoding:freeWhenDone: initWithCharacters:length:initWithCharactersNoCopy:length:freeWhenDone:
initWithString: initWithCString:encoding: initWithUTF8String: initWithFormat: initWithFormat:arguments: initWithFormat:locale:initWithFormat:locale:arguments:
initWithData:encoding: stringWithFormat: localizedStringWithFormat: stringWithCharacters:length: stringWithString: stringWithCString:encoding:
stringWithUTF8String: stringWithCString: Deprecated in Mac OS X v10.4 stringWithCString:length: Deprecated in Mac OS X v10.4
initWithCString: Deprecated in Mac OS X v10.4 initWithCString:length: Deprecated in Mac OS X v10.4 initWithCStringNoCopy:length:freeWhenDone: Deprecated in Mac OS X v10.4
 NSMutableString
appendFormat: appendString: deleteCharactersInRange:  insertString:atIndex:  replaceCharactersInRange:withString:
replaceOccurrencesOfString:withString:options:range: setString:


 NSLog
 NSAffineTransform NSAppleEventDescriptor NSAppleEventManager NSAppleScript NSArchiver NSArray
 NSAssertionHandler NSAttributedString NSAutoreleasePool NSBlockOperation NSBundle NSCache
 NSCachedURLResponse NSCalendar NSCharacterSet NSClassDescription NSCloneCommand NSCloseCommand
 NSCoder NSComparisonPredicate NSCompoundPredicate NSCondition NSConditionLock NSConnection NSCountCommand
 NSCountedSet NSCreateCommand NSData NSDataDetector NSDate NSDateComponents NSDateFormatter NSDecimalNumber
 NSDecimalNumberHandler NSDeleteCommand NSDeserializer NSDictionary NSDirectoryEnumerator NSDistantObject
 NSDistantObjectRequest NSDistributedLock NSDistributedNotificationCenter NSEnumerator NSError NSException
 NSExistsCommand NSExpression NSFileHandle NSFileManager NSFileWrapper NSFormatter NSGarbageCollector NSGetCommand
 NSHashTable NSHost NSHTTPCookie NSHTTPCookieStorage NSHTTPURLResponse NSIndexPath NSIndexSet NSIndexSpecifier
 NSInputStream NSInvocation NSInvocationOperation NSInteger NSKeyedArchiver NSKeyedUnarchiver NSLinguisticTagger
 NSLocale NSLock NSLogicalTest NSMachBootstrapServer NSMachPort NSMapTable NSMessagePort NSMessagePortNameServer
 NSMetadataItem NSMetadataQuery NSMetadataQueryAttributeValueTuple NSMetadataQueryResultGroup NSMethodSignature
 NSMiddleSpecifier NSMoveCommand NSMutableArray NSMutableAttributedString NSMutableCharacterSet NSMutableData
 NSMutableDictionary NSMutableIndexSet NSMutableSet NSMutableString NSMutableURLRequest NSNameSpecifier
 NSNetService NSNetServiceBrowser NSNotification NSNotificationCenter NSNotificationQueue NSNull
 NSNumber NSNumberFormatter NSObject NSOperation NSOperationQueue NSOrderedSet NSOrthography
 NSOutputStream NSPipe NSPointerArray NSPointerFunctions NSPort NSPortCoder NSPortMessage NSPortNameServer
 NSPositionalSpecifier NSPredicate NSProcessInfo NSPropertyListSerialization NSPropertySpecifier NSProtocolChecker NSProxy
 NSQuitCommand NSRandomSpecifier NSRangeSpecifier NSRecursiveLock NSRegularExpression NSRelativeSpecifier NSRunLoop NSScanner
 NSScriptClassDescription NSScriptCoercionHandler NSScriptCommand NSScriptCommandDescription NSScriptExecutionContext NSScriptObjectSpecifier
 NSScriptSuiteRegistry NSScriptWhoseTest NSSerializer NSSet NSSetCommand NSSocketPort NSSocketPortNameServer NSSortDescriptor
 NSSpecifierTest NSSpellServer NSStream NSString NSTask NSTextCheckingResult NSThread NSTimer NSTimeZone NSUnarchiver NSUndoManager
 NSUniqueIDSpecifier NSURL NSURLAuthenticationChallenge NSURLCache NSURLConnection NSURLCredential
 NSURLCredentialStorage NSURLDownload NSURLHandle NSURLProtectionSpace NSURLProtocol NSURLRequest NSURLResponse
 NSUserDefaults NSValue NSValueTransformer NSWhoseSpecifier NSXMLDocument NSXMLDTD NSXMLDTDNode NSXMLElement
 NSXMLNode NSXMLParser  NSCoding NSComparisonMethods NSConnectionDelegate NSCopying NSDecimalNumberBehaviors
 NSErrorRecoveryAttempting NSFastEnumeration NSFileManagerDelegate NSKeyedArchiverDelegate NSKeyedUnarchiverDelegate
 NSKeyValueCoding NSKeyValueObserving NSLocking NSMachPortDelegate NSMetadataQueryDelegate NSMutableCopying
 NSNetServiceBrowserDelegate NSNetServiceDelegate NSObjCTypeSerializationCallBack NSObject NSPortDelegate
 NSScriptingComparisonMethods NSScriptKeyValueCoding NSScriptObjectSpecifiers NSSpellServerDelegate
 NSStreamDelegate NSURLAuthenticationChallengeSender NSURLHandleClient NSURLProtocolClient NSXMLParserDelegate
*/
 

Декілька слів:
Нажаль @synthesize в мене покищо не запрацював, тому прийшлось писати set і get* методи, але я намагаюсь якось це побороти. Метод description еквівалентний toString() з Java. З іншим, я думаю, проблем не має бути.

Немає коментарів:

Дописати коментар