object-c基础总结

最近在学习ios编程,总结一下object-c.

C语言中声明一个函数是这样的

void SomeFunction(SomeType value);

object-c中这样定义

- (void)someMethodWithValue:(SomeType)value;

前面的减号表示类实例的方法,类的实例可以调用;如果是加号,表示类的方法,类本身可以调用,object-c的类也是对象。

多个参数的话这样传

- (void)someMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2;
value1和value2是接收方法调用时传入的参数的。

1
2
3
4
@interface XYZPerson : NSObject
@property (readonly) NSString *firstName;
@property (readonly) NSString *lastName;
@end

NSString类的方法有

1
2
3
4
5
+ (id)string;
+ (id)stringWithString:(NSString *)aString;
+ (id)stringWithFormat:(NSString *)format, …;
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;

定义一个类要先在interface里声明,再在implementation中定义

1
2
3
4
5
6
7
8
9
10
11
12
@interface XYZPerson:NSObject
@property (readonly) NSString *firstName;
@property (readonly) NSString *lastName;
@property (readonly) NSDate *birtyDate;
- (void)sayHello;
@end
@implementation XYZPerson
- (void)sayHello {
NSLog(@"Hello World!");
}
@end