单身类iPhone [英] Singleton Class iPhone

查看:113
本文介绍了单身类iPhone的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我试图避免全局变量,所以我读了单身类。
这是尝试设置和读取一个可变数组,但结果为空。

  //内容。 h 

@interface内容:NSObject {
NSMutableArray * contentArray;
}

+(Content *)sharedInstance;

- (NSMutableArray *)getArray;
- (void)addArray:(NSMutableArray *)mutableArray;


@end

  // Content.m 

@implementation内容



静态内容* _sharedInstance;

+(Content *)sharedInstance
{
if(!_sharedInstance)
{
_sharedInstance = [[Content alloc] init];
}

return _sharedInstance;
}

- (NSMutableArray *)getArray {
return contentArray;


$ b - (void)addArray:(NSMutableArray *)mutableArray {

[contentArray addObject:mutableArray];

}

@end

一个ViewController我添加了#importContent.h,我尝试调用它:

  NSMutableArray * mArray = [NSMutableArray arrayWithObjects :@ 测试,@ foo 的,@ 酒吧,零]。 

内容* content = [Content sharedInstance];
[content addArray:mArray];

NSLog(@contentArray:%@,[content getArray]);


解决方案

您需要首先分配并初始化数组。就个人而言,我会在内容类的init方法中这样做:

   - (id)init {
if(self = [super init]){
...其余的init代码...
contentArray = [[NSMutableArray alloc] init];
}

返回自我;
}


Ok, I'm trying to avoid global variables, so I read up on singleton classes. This is a try to set and read a mutable array, but the result is null.

//Content.h

@interface Content : NSObject {
    NSMutableArray *contentArray;
}

+ (Content *) sharedInstance;

- (NSMutableArray *) getArray;
- (void) addArray:(NSMutableArray *)mutableArray;


@end

.

//Content.m

@implementation Content



static Content *_sharedInstance;

+ (Content *) sharedInstance
{
    if (!_sharedInstance)
    {
        _sharedInstance = [[Content alloc] init];
    }

    return _sharedInstance;
}

- (NSMutableArray *) getArray{
    return contentArray;

}

- (void) addArray:(NSMutableArray *)mutableArray{

    [contentArray addObject:mutableArray];  

}

@end

And in a ViewController I added #import "Content.h", where I try to call this:

NSMutableArray *mArray = [NSMutableArray arrayWithObjects:@"test",@"foo",@"bar",nil];

Content *content = [Content sharedInstance];
[content addArray:mArray];

NSLog(@"contentArray: %@", [content getArray]);

解决方案

You need to alloc and init the array first. Personally I'd do it in the init method of the content class like so:

-(id)init{
    if(self = [super init]){
        …the rest of your init code… 
        contentArray = [[NSMutableArray alloc] init];
    }

    return self;
}

这篇关于单身类iPhone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆