Objective-C語法小總結

1,方法調用


    (1)調用對象的方法:

output = [object methodWithOutput]; 
output = [object methodWithInputAndOutput:input];

    (2)調用類的方法:(創建對象)

id myObject = [NSString string]; 
NSString* myString = [NSString string]; 

    (3)嵌套調用:

[NSString stringWithFormat:[prefs format]];

    (4)多輸入參數:

聲明:
-(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile; 
調用:
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];

2.訪問器


    (1)setter

[photo setCation:@”Day at the Beach”];
output = [photo caption];

    (2)點操作符

photo.caption = @”Day at the Beach”; 
output = photo.caption; 

3.創建對象


    (1)創建自動釋放的對象

NSString* myString = [NSString string];

    (2)手工alloc創建

NSString* myString = [[NSString alloc] init]; 

    注:[NSString alloc] 是NSString類本身的alloc方法調用。這是一個相對低層的調用,它的作用是分配內存及實例化一個對象。

            [[NSString alloc] init] 調用新創建對象的init方法。init方法通常做對象的初始化設置工作,比如創建實例變量。


4.內存管理


//string1 將被自動釋放 
NSString* string1 = [NSString string]; 
 
//必須在用完後手工釋放 
NSString* string2 = [[NSString alloc] init]; 
[string2 release]; 

5.類接口


Photo.h
#import <Cocoa/Cocoa.h> 
 
@interface Photo : NSObject { 
   NSString* caption; 
   NSString* photographer; 
} 
 
- (NSString*)caption; 
- (NSString*)photographer; 
 
- (void) setCaption: (NSString*)input; 
- (void) setPhotographer: (NSString*)input; 

6.類實現


Photo.m

#import "Photo.h" 
 
@implementation Photo 
 
- (NSString*) caption { 
    return caption; 
} 
 
- (NSString*) photographer { 
    return photographer; 
} 
 
- (void) setCaption: (NSString*)input 
{ 
    [caption autorelease]; 
    caption = [input retain]; 
} 
 
- (void) setPhotographer: (NSString*)input 
{ 
    [photographer autorelease]; 
    photographer = [input retain]; 
} 
- (void) dealloc 
{ 
    [caption release]; 
    [photographer release]; 
    [super dealloc]; 
}
@end

7.日誌記錄: NSLog()


NSLog ( @"The current date and time is: %@", [NSDate date] );

8.屬性(Property)


用屬性改寫後的接口:

#import <Cocoa/Cocoa.h> 
 
@interface Photo : NSObject { 
    NSString* caption; 
    NSString* photographer; 
} 
@property (retain) NSString* caption; 
@property (retain) NSString* photographer; 
 
@end 

改寫後的實現部分:

#import "Photo.h" 
         
@implementation Photo 
 
@synthesize caption; 
@synthesize photographer; 
 
- (void) dealloc 
{ 
    self.caption = nil; 
    self.photographer = nil;
    [super dealloc]; 
} 
 
@end

9.類目(Category)


聲明:

#import <Cocoa/Cocoa.h> 
             
@interface NSString (Utilities) 
- (BOOL) isURL; 
@end 

實現:

#import "NSString-Utilities.h" 
             
@implementation NSString (Utilities) 
 
- (BOOL) isURL 
{ 
    if ( [self hasPrefix:@"http://"] ) 
        return YES; 
    else 
        return NO; 
} 
 
@end







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章