2012-01-25 41 views
0

我試圖存儲幾個字符串在我的... NSUserDefaults的想不通我做錯了什麼......不會儲存我的NSString的

-(IBAction)addToFavorite:(id)sender { 
    NSMutableArray* favoritedAlready = [[[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"] mutableCopy]; 

NSLog(@"%@",favoritedAlready); 


    if (![favoritedAlready containsObject:indexPathRowString]) { 
     [favoritedAlready addObject:indexPathRowString]; 
     [[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:@"favorites"]; 
     [[NSUserDefaults standardUserDefaults] synchronize]; 
     favoritMarkerad.image = [UIImage imageNamed:@"StarFilled.png"];} 

    else { 
     [favoritedAlready removeObject:indexPathRowString]; 
     [[NSUserDefaults standardUserDefaults] setObject:favoritedAlready forKey:@"favorites"]; 
     [[NSUserDefaults standardUserDefaults] synchronize]; 
     favoritMarkerad.image = [UIImage imageNamed:@"StarEmpty.png"]; 
    } 

當我嘗試載入我的陣列中的另一個視圖 - 控制沒有任何反應..

(.h) 
NSMutableArray *favorites_; 
@property (nonatomic, retain) NSMutableArray *favorites_; 

(.m) 
@synthesize favorites_; 

-(void)makeData{ 

NSMutableArray* favoritedAlready = [[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 

    favorites_ = favoritedAlready;} 

「的NSLog(@」 %@ 「favoritedAlready);」給出「2012-01-25 14:53:26.360 myApp [2752:1be03](null)」 有什麼想法?

+0

什麼DOE你當你'的NSLog(@「% @「,favoritedAlready);'在'mutableCopy'方法之後? 「 – basvk

+0

」2012-01-25 14:52:07.385 myapplication [2714:1be03](null)「 – Christoffer

+0

您將字符串放入數組中並將其存儲並且您的邏輯似乎是,如果字符串尚未存在那麼你添加它,如果它已經存在,那麼你刪除它?這一切是否準確?就產量而言,當你期望時,你大概不會看到「新增喜愛」?你有沒有嘗試NSLogging實際的數組看看有什麼在那裏作爲診斷步驟? – Tommy

回答

2

根據您的評論,問題是您的NSUserDefaults在任何時候都沒有名爲'收藏夾'的數組。可能你想創建一個,如果它不存在。所以:

-(IBAction)addToFavorite:(id)sender { 
    // get a mutable copy of the stored array, if there is one 
    NSMutableArray* favoritedAlready = [[[NSUserDefaults standardUserDefaults] 
        objectForKey:@"favorites"] mutableCopy]; 

    // if there wasn't a stored array then go ahead and create one to store 
    if(!favoritedAlready) 
     favoritedAlready = [NSMutableArray array]; 

    /* ... rest of stuff here ... */ 
    if (![favoritedAlready ... 
+0

歡呼聲,甚至沒有想到回合! – Christoffer

1

的NSMutableArray的是(空)在第一點,所以你可以這樣做:在mutableCopy方法之後

if (favoritedAlready == nil) { 
     favoritedAlready = [[NSMutableArray alloc] init]; 
    } 

。 所以你就可以添加值到NSMutableArray,而不是將其添加到(空)對象的


就像湯米說

+0

非常感謝! :) – Christoffer

+0

@basvk抱歉關於篡奪你;在Christoffer發佈評論後,我剛好碰巧在這裏發現了答案。從我+1。 – Tommy

+0

NP。你快了;) – basvk