Working with Objects
Objects Send and Receive Messages
对象发送和接受消息
.h定义
@interface XYZPerson : NSObject
- (void)sayHello;
@end
.m实现
@implementation XYZPerson
- (void)sayHello {
NSLog(@"Hello, world!");
}
@end
//实例化
//实例化person类
//XYZPerson *per = [[XYZPerson alloc] init];
//调用方法
//[per sayHello];
//释放内存
//[per release];
Use Pointers to Keep Track of Objects
使用指针定位对象
Methods Can Return Values
返回值
Objects Can Send Messages to Themselves
调用本身方法
Objects Can Call Methods Implemented by Their Superclasses
Objects Are Created Dynamically
对象是动态创建的
The NSObjectroot class provides a class method,alloc, which handles this process for you:
NSObject提供了一个方法
+ (id)alloc; //分配内存空间、实例化对象
You need to combine a call toallocwith a call to init, anotherNSObjectmethod:
NSObject提供了另一个方法初始化值
- (id)init; //初始化对象的成员
//实际实例化一个对象要如下使用
NSObject *newObject = [[NSObject alloc] init];//object中的连贯操作类似NSObject->alloc->init
Initializer Methods Can Take Arguments
The NSNumberclass defines several initializers, including:
- (id)initWithBool:(BOOL)value;
- (id)initWithFloat:(float)value;
- (id)initWithInt:(int)value;
- (id)initWithLong:(long)value;
NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];
Use new to Create an Object If No Arguments Are Needed for Initialization (暂时无实用价值)
XYZObject *object = [XYZObject new];
// is effectively the same as:等价于
XYZObject *object = [[XYZObject alloc] init];
Literals Offer a Concise Object-Creation Syntax
You can create an NSString instance, for example, using a special literal notation, like this:
NSString *someString = @"Hello, World!";
NSString *someString = [NSString stringWithCString:"Hello, World!"
encoding:NSUTF8StringEncoding];
NSNumber *myBOOL = @YES;
NSNumber *myFloat = @3.14f;
NSNumber *myInt = @42;
NSNumber *myLong = @42L;
NSNumber *myInt = @(84 / 2);
Objective-C Is a Dynamic Language
object-c是一种动态语言
id someObject = @"Hello, World!";//id代表任何类型(id其实是一个object-c对象的指针,必须是NS开头的)
不要写成 id *someObject(不用带*)
Determining Equality of Objects
对象的比较
When dealing with objects, the == operator is used to test whether two separate pointers are pointing to thesame object:
if (firstPerson == secondPerson) {//2个对象比较是否指向一个内存地址(是否是一个对象) // firstPerson is the same object as secondPerson
}
比较2个对象的值是否相等要用如下
if ([firstPerson isEqual:secondPerson]) {
// firstPerson is identical to secondPerson
}
//比较2个对象的大小,如下比较someDate和anotherDate的大小
//IOS中的3个预定义变量
NSOrderedAscending = -1
NSOrderedSame = 0
NSOrderedDescending= 1
if ([someDate compare:anotherDate] == NSOrderedAscending) {
// someDate is earlier than anotherDate
}
Working with nil
一般给变量或对象初始化值是个好习惯
下面情况编译器会给对象默认为nil空
XYZPerson *somePerson;
// somePerson is automatically set to nil
如果你返回一个nil值作为返回值,对应返回值类型,object-》nil,numeric-》0,BOOL-》NO
判断
if (somePerson != nil) {
// somePerson points to an object
}
if (somePerson) {
// somePerson points to an object
}