Objective-C语法小总结

来源:互联网 发布:湖南大学软件工程硕士 编辑:程序博客网 时间:2024/05/01 14:10

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







原创粉丝点击