use*_*991 0 memory-management allocation objective-c
我不确定如何初始化Objective-C类中的各种属性.请假设我在你的答案中是Objective-C的新用户......
我有以下课程:
考试班
@interface Test : NSObject
@property (nonatomic, strong) NSString *name;
@end
Run Code Online (Sandbox Code Playgroud)
TestManager类
@interface TestManager : NSObject
@property (nonatomic, strong) NSMutableArray *tests; // array of Test objects (array size unknown until runtime)
@end
Run Code Online (Sandbox Code Playgroud)
控制器类
@interface TestController : NSObject
@property (nonatomic, strong) TestManager *aManager;
-(void)initManager;
-(void)doSomething;
@end
Run Code Online (Sandbox Code Playgroud)
我想要一个像initManager被调用的方法:
-(void)initManager
{
// how can I init the aManager which will have an array of Test objects
}
Run Code Online (Sandbox Code Playgroud)
它将自动分配一个对象数组,以存储在manager类中,这样我就可以执行以下操作:
-(void)doSomething
{
NSString *name = ((Test *)[self.aManager.tests objectAtIndex:0]).name;
}
Run Code Online (Sandbox Code Playgroud)
我甚至不确定initManager是否是正确的使用方法 - 内置的内容总是被调用吗?
首先,让我们看看我们初始化Test类对象的方式.
您还可以为Test类编写一些初始化方法,而不是这样:
Test example = [[Test alloc] init];
example.name = @"s";
Run Code Online (Sandbox Code Playgroud)
你可以写这样的东西:
Test example = [[Test alloc] initWithName:@"s"];
Run Code Online (Sandbox Code Playgroud)
请注意,这对于初始化方法返回新创建的对象非常常见,因此初始化方法通常返回'id'类型(不是void).
这是您的测试类的实现,将在下面的示例中使用.
.h文件:
- (id)initWithName:(NSString *)aName;
Run Code Online (Sandbox Code Playgroud)
.m文件:
- (id)initWithName:(NSString *)aName
{
self = [super init];
if (self) {
_name = aName;
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
您可以这样初始化TestController类:
.h文件:
- (id)initManager;
Run Code Online (Sandbox Code Playgroud)
.m文件:
- (id)initManager
{
self = [super init]; //always call the superclass init method when your class inherit from other class
if (self) { // checking if the superclass initialization was fine
_tests = [NSMutableArray array];
[_tests addObject:[[Test alloc] initWithName:@"s"]];
[_tests addObject:[[Test alloc] initWithName:@"l"]];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
或类似的东西:
- (id)initManager
{
self = [super init]; //always call the superclass init method when your class inherit from other class
if (self) { // checking if the superclass initialization was fine
_tests = [NSArray arrayWithObjects:[[Test alloc] initWithName:@"s"], [[Test alloc] initWithName:@"l"]];
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
就像@Andrew说的那样,最好使用alloc + init.以下是此语法的一些示例:
CGRect rect = CGRectMake(0, 0, 100, 100);
[[UIView alloc] initWithFrame:rect];
[[NSArray alloc] init]
Run Code Online (Sandbox Code Playgroud)
这是初始化对象的常用方法.尽管有这种机制,但还有一些额外的方法(实际上是静态函数),它们为程序员提供了初始化对象的好方法.使用它们你不必编写关键字'alloc',这样代码就更短,更容易阅读.
[NSArray array] //creates and returns empty array
[NSMutableArray array] //creates and return empty mutable array
[UIButton buttonWithType:UIButtonTypeContactAdd]; //creates and return button
Run Code Online (Sandbox Code Playgroud)