2014-01-16 34 views
-1

我想通過使用Singleton傳遞一個對象,但是當我在新的ViewController中打印它時,它給了我(null)。當我在Viewcontroller1中NSLog optionsSingle時,它打印出對象。Singleton Return(null)

Viewcontroller1.h

@interface PrivateViewController : UIViewController<UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate> 
{ 
    rowNumber *optionsSingle; 
} 

Viewcontroller1.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    optionsSingle = [rowNumber singleObj]; 
    optionsSingle = [devices objectAtIndex:indexPath.row];  
} 

Viewcontroller2.h

@interface SelectVideo : UITableViewController<NSFetchedResultsControllerDelegate> 
{ 
    rowNumber *optionsSingle; 
} 

Viewcontroller2.m

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    optionsSingle=[rowNumber singleObj]; 
    NSLog(@"%@", [NSString stringWithFormat:@"%@", optionsSingle.selectedRowNow]); 
} 

row.h

@interface rowNumber : NSObject 
{ 
    NSMutableArray *selectedRowNow; 
} 

@property (nonatomic) NSMutableArray *selectedRowNow; 

+(rowNumber *)singleObj; 

@end 

row.m

@implementation rowNumber 
{ 
    rowNumber *anotherSingle; 
} 

@synthesize selectedRowNow; 

+(rowNumber *)singleObj 
{ 
    static rowNumber * single=nil; 
    @synchronized(self) { 
     if(!single) { 
      single = [[rowNumber alloc] init]; 
     } 
    } 
return single; 
} 

@end 
+2

按照慣例,類名以大寫字母開頭。在可能的情況下,類的文件名與類名相同。這可以防止混淆,並讓其他人更容易理解其他代碼。 – zaph

+1

我懷疑這個單身人士的使用是有保證的。基本上單身人士應該非常謹慎地使用,不僅僅是爲了在對象之間傳遞一個值。 – zaph

回答

1

您應該創建單是這樣的:

static id shared_ = nil; 
static dispatch_once_t onceToken; 
dispatch_once(&onceToken, ^{ 
    shared_ = [[[self class] alloc] init]; 
}); 
return shared_; 
在viewController1.m

另外:

optionsSingle = [rowNumber singleObj]; 
optionsSingle = [devices objectAtIndex:indexPath.row]; 

第二林e使第一行無用。

你也在嘗試記錄一些東西,從外觀上看,你永遠不會創建或設置。我看不到你在哪裏設置'selectedRowNow' - 你應該重寫rowNumber類中的init方法來創建可變的'selectedRowNow'數組。

+0

你不需要'[self class]',只需'self'。在類方法中,'self'是類。 –

-1

您將創建一個單這樣簡單的方法

在您的.h文件寫入給婁代碼

@interface MySingleton : NSObject { 
    NSMutableArray *selectedRowNow; 
} 
+(MySingleton *)sharedInstance; 

下一步是在.m文件寫婁代碼

@implementation MySingleton 
static MySingleton *sharedInstance = nil; 

+ (MySingleton *)sharedInstance { 
    @synchronized(self) { 
     if (sharedInstance == nil) { 
      sharedInstance = [[MySingleton alloc] init]; 
     } 
    } 
    return sharedInstance; 
} 
+ (id)allocWithZone:(NSZone *)zone { 
    @synchronized(self) { 
     if (sharedInstance == nil) { 
      sharedInstance = [super allocWithZone:zone]; 
      return sharedInstance; 
     } 
    } 
    return nil; 
} 

- (id)copyWithZone:(NSZone *)zone { 
    return self; 
} 
- (id)init { 
    if ((self = [super init])) { 
} 
    return self; 
} 

之後,您可以在.pch文件或常量文件中定義此波紋代碼以減少代碼

#define AppSingleton [MySingleton sharedInstance] 

然後調用像

AppSingleton = [devices objectAtIndex:indexPath.row]; 

編碼愉快!

+0

這是矯枉過正,目前的最佳做法是使用'dispatch_once'。 – zaph