Objective-C语法小总结
2013-01-31 11:02
513 查看
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
相关文章推荐
- Objective-C语法总结收集
- Objective-C语法基础:面向对象编程特点的总结
- 黑马程序员——Objective-C之特殊语法总结
- 黑马程序员——Objective-C语言知识点总结之OC特有语法
- 小寒假第七天总结 转 Objective-C语法:
- 11-Objective-C特有语法:内存管理总结
- 【IOS 开发学习总结-OC-12】★objective-c面向对象之——合成存取方法与点语法
- Objective-C语法之动态类型常用方法总结
- #Objective - C NSString的常用语法点总结
- 《黑马程序员》 细节总结(Objective - c语法)
- Objective-C字面量语法总结
- iOS开发 入门学习总结(二)Objective-C 语法特性总结
- Objective-C语法总结
- Objective-C 语法总结
- Objective C Programming( OC ) 语法特点总结
- Objective-C字面量语法总结
- Objective-C字面量语法总结
- Objective-C的基础语法总结
- 黑马程序员——Objective-C基础——语法总结
- 【黑马程序员】---Objective-C核心语法总结