Objective-C中的加号和减号代表什么?
在OC中,方法分为类方法和实例方法:
1、前置加号(+)的方法为类方法,这类方法是可以直接用类名来调用(不能使用实例调用,这点和C++中的静态方法一样),它的作用主要是创建一个实例。有人把它称为创建实例的工厂方法。
2、前置减号(-)的方法为实例方法,必须使用类的实例才可以调用。
@interface TestClass1 : NSObject
@end
@implementation TestClass1
//类方法,只能通过类名来调用,不属于任何对象
+(TestClass1 *)instance{
return [[TestClass1 alloc] init];
}
//对象方法,通过对象来调用,所有对象都可以调用
-(void)testPrint{
NSLog(@"this is test string");
}
@end
-(void)main{
TestClass1 *testClassObj1 = [[TestClass1 alloc] init];
//调用减号方法,使用对象调用
[testClassObj1 testPrint];//输出 this is test string
//调用加号方法,使用类调用
[TestClass1 instance]; //输出 自身实例
}
3、类方法不能调用interface和implementation中的定义的成员变量
@interface V2TIMManager_pinConversation : XCTestCase
@end
@implementation V2TIMManager_pinConversation{
NSString *userID; //类成员变量
NSString *toUserId; //类成员变量
}
+ (void)testCall {
//错误的调用,会提示错误:Instance variable 'userID' accessed in class method
userID = @"test_xx";
}
- (void)setUp {
[super setUp];
userID = @"iOS_006"; //正确的调用
toUserId = @"iOS_0010";
}