我试图在创建自定义类的实例时自动初始化一个数组:
Sections.h
#import <Foundation/Foundation.h>
@interface Sections : NSObject {
NSMutableArray* allSections;
}
@property(nonatomic, strong) NSMutableArray* allSections;
@end
Sections.m
-(void)setAllSections:(NSMutableArray *)allSections {
//--This method sets the array of all the sections available on the app.
NSMutableArray *array = [[NSMutableArray alloc] init];
Section* sectionA = [Section alloc];
sectionA.htmlForExplanation = @"hello";
sectionA.description = @"section a description";
sectionA.name = @"section A";
sectionA.SectionId = 1;
[array addObject:sectionA];
Section* sectionB = [Section alloc];
sectionB.htmlForExplanation = @"hello";
sectionB.description = @"section B description";
sectionB.name = @"section B";
sectionB.SectionId = 2;
[array addObject:sectionB];
[allSections setArray:array.mutableCopy];
}
所以现在当我创建它的实例时,我想要一个预先填充的 allSections 数组
- (void)viewDidLoad
{
//GET DATA FOR SECTIONS POPULATE WEB VIEWS
Sections *sections = [[Sections alloc] init];
//ections setAllSections:<#(NSMutableArray *)#>]
Section* sectionA = [sections.allSections objectAtIndex:0];
Section* sectionB = [sections.allSections objectAtIndex:1];
[webViewA loadHTMLString:sectionA.name baseURL:nil];
[webViewB loadHTMLString:sectionB.name baseURL:nil];
[super viewDidLoad];
}
然而这些对象看起来是空的?这是在 Objective-C 中自动创建数组的正确方法吗?
最佳答案
不,您使用的是设置而不是 setter/getter 。
如果在 init
中填充数组会更好。
Sections.h
#import <Foundation/Foundation.h>
@interface Sections : NSObject {
NSMutableArray* allSections;
}
@property(nonatomic, strong) NSMutableArray* allSections;
@end
Sections.m
#import "Sections.h"
@implementation
@synthesize allSections
- (id) init {
self = [super init];
if (self) {
allSections= [[NSMutableArray alloc] init];
Section* sectionA = [Section alloc];
sectionA.htmlForExplanation = @"hello";
sectionA.description = @"section a description";
sectionA.name = @"section A";
sectionA.SectionId = 1;
[allSections addObject:sectionA];
Section* sectionB = [Section alloc];
sectionB.htmlForExplanation = @"hello";
sectionB.description = @"section B description";
sectionB.name = @"section B";
sectionB.SectionId = 2;
[allSections addObject:sectionB];
}
return self;
}
@end
如您所见,sections 的实现不包含 allSections 的任何 setter 或 getter。这些是使用 @synthesize
指令为您创建的。
关于objective-c - 自动在 nsobject 中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12817914/