当我在玩 Objective-C 时,我刚刚制作了一个简短的示例演示程序来取乐:
一些代码:
// TestClass.h:
@interface TestClass : NSObject {
int someNumber;
float someFloat;
}
@property int someNumber;
@property float someFloat;
// Returns String containing some instance values:
-(NSString *)getNiceString;
// Returns always the same string:
-(NSString *)getAnotherString;
-(id)init;
@end
--
//TestClass.m:
#import "TestClass.h"
@implementation TestClass
@synthesize someFloat;
@synthesize someNumber;
-(NSString*) getNiceString{
return [NSString stringWithFormat:
@"Float number: %f and the number is: %d", self.someFloat, self.someNumber];
}
-(NSString *) getAnotherString{
return [NSString stringWithString:@"TEST STRING"];
}
-(id)init{
self = [super init];
if(self){
self.someFloat = 100.34;
self.someNumber = 324;
return self;
}
return nil;
}
@end
还有一些主要内容:
#import <Foundation/Foundation.h>
#import "TestClass.h"
int main (int argc, const char * argv[])
{
@autoreleasepool {
TestClass* instance = [TestClass alloc];
// Version 2:
// TestClass* instance = [[TestClass alloc]init];
NSLog(@"%@", [instance getNiceString]);
NSLog(@"%@", [instance getAnotherString]);
}
return 0;
}
当我TestClass* instance = [TestClass alloc];
在 main 中使用时,输出是:
2013-03-05 09:56:34.767 ObjectiveTest[8367:903] 浮点数:0.000000,数字为:0 2013-03-05 09:56:34.770 ObjectiveTest[8367:903] 测试字符串
当使用第二个版本时(TestClass* instance = [[TestClass alloc]init];
):
2013-03-05 10:06:46.743 ObjectiveTest[8421:903] 浮点数:100.339996,数字为:324 2013-03-05 10:06:46.750 ObjectiveTest[8421:903] 测试字符串
The question is if [TestClass alloc]
makes any initialization stuff (String is returned properly and values are zeros)... It is worth to mention that if I remove the -(id)init:
implementation from TestClass.m the outputs for versions with init
and without it are exactly the same... Is there any default initialization?