0

我是 Xcode 的新手,我正在尝试用数组和字典创建一个类。我不明白如何正确初始化对象。我究竟做错了什么?

“主数据.h”

#import <Foundation/Foundation.h>

@interface maindata : NSDictionary
{
    NSDictionary *maindict;
    NSArray      *arrayofallmethods;
    NSArray      *categories;
    NSArray      *methods;
}

@property(nonatomic,retain) NSDictionary *maindict;
@property(nonatomic,retain) NSArray      *categories;
@property(nonatomic,retain) NSArray      *methods;
@property(nonatomic,retain) NSString     *pathtoplist;


+(maindata *) shareddata;

@end

“主数据.m”

#import "maindata.h"

@implementation maindata

@synthesize maindict;
@synthesize methods;
@synthesize categories;
@synthesize pathtoplist;

static maindata *shareddata_;

-(id)init
{
    if(self == [super init])
    {
        pathtoplist = [[NSBundle mainBundle] pathForResource:@"allData" ofType:@"plist"];
        shareddata_.maindict = [NSMutableDictionary dictionaryWithContentsOfFile:pathtoplist];
        shareddata_.methods = [maindict allValues];
    }

    return shareddata_;
}

+(maindata *) shareddata
{
    if (!shareddata_)
    {
        shareddata_ = [[maindata alloc] init];
    }

    return shareddata_;
}

@end
4

2 回答 2

1

您在这里创建的似乎是单例对象。如果你故意这样做,那很好。但是,要正常初始化一个对象,您应该只使用-(id)init没有静态共享内容的方法。

所以基本上你应该遵循吉姆的回答。注意线

-(id)init
{
    if(self == [super init]){}
}

不是比较,而是赋值,所以应该是这样的

-(id)init
{
    if(self = [super init]){}
}

或者,为避免编译器警告,您可以编写

-(id)init
{
    self=[super init];
    if(self){}
}
于 2012-04-13T11:07:24.173 回答
0
//maindata.h
#import <Foundation/Foundation.h>
@interface maindata : NSObject{
         NSDictionary *maindict;
         NSArray      *arrayofallmethods;
         NSArray      *categories;
         NSArray      *methods;
}
@property(nonatomic,retain) NSDictionary *maindict; 
@property(nonatomic,retain) NSArray *categories;
@property(nonatomic,retain) NSArray *methods;
@property(nonatomic,retain) NSArray * arrayofallmethods;
@end


//"maindata.m"

import "maindata.h"
@implementation maindata
@synthesize maindict;
@synthesize methods;
@synthesize categories;
@synthesize arrayofallmethods;

-(id)init {
      if(self = [super init]){
          NSString *pathtoplist = [[NSBundle mainBundle] pathForResource:@"allData" ofType:@"plist"];
          maindict = [NSMutableDictionary dictionaryWithContentsOfFile:pathtoplist];
          methods = [maindict allValues];
    }
    return self;
 }
@end

并从其他类尝试初始化和创建 maindata 类的对象

#import <UIKit/UIKit.h>
#import "maindata.h"

int main(int argc, char *argv[]) {
     maindata *objMainData = [[maindata alloc]init];
     // use object here for more operations on your data.
}
于 2012-04-13T11:00:36.397 回答