《学习Objective-C》

来源:互联网 发布:程序员真的那么累吗 编辑:程序博客网 时间:2024/06/07 00:52

《学习Objective-C》这篇文章涵盖了以下内容:

 

Objective-C的简单介绍

说明了为什么要学习Objective-C。

 

如何调用方法(函数)

作者首先用很简单例子介绍如何调用方法,这样读者可以更快进入Objective-C的语法。


如:[object method];

        [object methodWithInput:input];

返回一个值

     output = [object methodWithOutput];

     output = [object methodWithAndOutpu:input];

返回一个对象

    id myobject = [NSString string];

   NSString *myString = [NSString string];

 

方法的嵌套调用

介绍如何在方法中调用其他方法。

  

 [NSString stringWithFormat:[prefs format]];


多个参数的方法

这方面的内容本站也有相关介绍。

 

如:-(BOOL)writetoFile:(NSString*)path atomically:(BOOL)useAuxiliaryFile;


调用上面的方法

 BOOL result = [myData writetoFile:@"hello" atomically:NO]; 


获取及设置数值的方式

这部分介绍了Objective-C 1.x版本中如何获取和设置参数值以及如何使用Objective-C 2.0的“点”语法获取和设置属性值。

 


[photo setCaption:@"Day at the Beach"];

 output = [photo caption];

或者

photo.caption = @"Day at the Beach"; 

output = photo.caption;


如何创建对象

这部分介绍了Objective-C创建对象的方式。


两种方式:1、NSString* myString = [NSString string];

                 2、 NSString* myString = [[NSString allocinit];  

第二种方式需要手动释放内存

             

基本的内存管理

这部分作者使用了两个简单例子,对Objective-C内存管理进行了简单的介绍。

   

         NSString* string1 = [NSString string];


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

        [string2 release];

如何设计类接口

这部分介绍了如何定义类的头文件、如何添加方法等方面的知识。

 

#import <Cocoa/Cocoa.h> @interface Photo : NSObject 

{ NSString* caption;

 NSString* photographer; 

- (void) setCaption: (NSString*)input;

- (void) setPhotographer: (NSString*)input;

 @end


如何实现一个类

继续通过例子讲解如何实现一个类。

 

#import "Photo.h" 

@implementation Photo


- (id) init

{

 if ( self = [super init] ) 

 { 

 [self setCaption:@"Default Caption"]; 

 [self setPhotographer:@"Default Photographer"];

 }

 return self; 

}


 - (NSString*) caption {

 return caption;

 } 


- (NSString*) photographer { 

return photographer; 

@end


深入了解内存管理

主要介绍Objective-C的alloc、retain、release的使用。


 Cocoa关于对象及保留计数器的3条规则:

1、如果使用new、alloc或copy操作获得一个对象,则该对象的保留计数器值为1。

2、如果通过其他任何方法获得一个对象,则假设该对象的保留计数器值为1,而且已经被设置为自动释放。

3、如果保留了某个对象,则必须保持retain方法和release方法的使用次数相等。

其实归结起来就一句话:如果使用了new、alloc或copy获得一个对象,则必须释放或自动释放该对象。


属性

介绍Objective-C 2.0中最新增加的属性的使用方法。

 

nil的调用介绍

介绍调用Objective-C空指针的方法。

 

类的分类

介绍了Objective-C的分类特性。

原创粉丝点击