用OBJC编程 2 - working with Objects
发送和接收消息@interface XYZPerson : NSObject
-(void) sayHello;
@end
// implemetation
@implementation XYZPerson
- (void) sayHello{
NSLog(@"Hello, world!");
}
@end // XYZPerson
// -----
[somePerson sayHello];
通过指针keep对象-(void)myMethod{
NSString *myString = // get a string from somewhere.
}
通过参数传递对象-(void)saySomething:(NSString *)greeting;
// implementation
-(void)saySomething:(NSString *)greeting{
NSLog(@"%@", greeting); // "%@",用来打印对象
}
通过返回值传递-(NSString *)magicString;
//implementation
-(NSString *)magicString{
NSString *stringToReturn = // create string
return stringToReturn;
}
// use it
NSString *magic = [testString magicString];
向自己发送消息@implementation XYZPerson
-(void)sayHello{
[self saySomething:@"Hello, world!"];
}
-(void)saySomething:(NSString *)greeting{
NSLog(@"%@", greeting);
}
@end
向父类发消息@interface XYZShoutingPerson : XYZPerson
@end
/////////////////////
@implementation XYZShoutingPerson
-(void)saySomething:(NSString *)greeting{
NSString *uppercaseGreeting = [greeting uppercaseString];
[super saySomething:uppercaseGreeting];
}
@end
动态创建对象// NSObject提供一个类方法, id like (NSObject *)
+(id)alloc;
//
-(id)init;
//=============== use it
NSObject *newObject = [[NSObject alloc] init];
// init可能返回一个和alloc不同的对象,因此最好嵌套使用alloc和init,不推荐如下使用
NSObjet *someObject = [NSObject alloc];
[someObject init];
初始化方法可以带参数-(id)initWithInt:(int)value;
-(id)initWithLong:(long)value;
//------------------
NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];
类工厂方法提供了另一个选择+(NSNumber *)numberWithInt:(int)value;
+(NSNumber *)numberWithLong:(long)value;
//------------------
NSNumber *magicNumber = [NSNumber numberWithInt:42];
使用new来代替XYZObject *object = [XYZObject new];
// is effectively the same as:
XYZObject *object = [[XYZObject alloc] init];
通过字面量创建NSString *someString = @"Hello, world!";
// is same as
NSString *someString = [NSString stringWithCString:"Hello, world!" encoding:NSUTF8StringEncoding];
//=======
NSNumber *myBOOL = @YES;
NSNumber *myFloat = @3.14f;
NSNumber *myInt = @42;
NSNumber *myLong = @42L;
NSNumber *myInt2 = @(84 / 2);
OBJC 是一个动态语言// 下面代码会产生运行时错误,因为NSString没有removeAllObjects方法
id someObject = @"Hello, World!";
[someObject removeAllObjects];
// 下面代码会产生编译时错误
NSString *someObject = @"Hello, World!";
[someObject removeAllObjects];
比较对象// 因为是指针,所以可以这样比较是否同一个对象
if(firstPerson == secondPerson){
// the same object
}
// 如果要比较数据是否相同,使用isEqual
if([firstPerson isEqual:secondPerson]) {
// is identical to second
}
使用nil// nil 是一个对象指针,声明一个对象指针无需初始化,编译器会初始化它为nil
XYZPerson *somePerson;
// ------------
if(somePerson != nil){
// ====
}
// or
if(somePerson){
// ===
}