2013-07-18 46 views
0

我在我的代碼中有一個NSMutableArray,我想訪問該數組的最後一個元素並將該元素保存在整數n變量中。但n不給我正確的價值,當我NSLog它,它給了我一個垃圾值。NSMutableArray不會返回值並分配給變量

for(int i=0;i<[array3 count];i++) 
    { 
     if(i==([array3 count]-1)) 
     { 
      n = [array3 objectAtIndex:i]; 
     }  
    } 

    NSLog(@"The id is=%d",n); 

    NSError *error; 
    NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
     NSString *dataPath = [aDocumentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",n]]; 
     [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; 
+1

如果n是int類型,它將不起作用。因爲數組只保存對象而int不是對象。 – user523234

+0

n是int類型的,但它給了我垃圾值。 – Nasir

+0

您不能直接將int存儲在NSMutableArray中。粘貼代碼添加對象的位置 –

回答

3

數組包含對象,而不是標量類型,如整數。試試這個代替:

id n = [array3 lastObject];   // prettier than objectAtIndex:[array count]-1 
NSLog(@"the last object is %@", n); // %@ is an object format descriptor 

也許數組包含NSNumbers有意義的整數?

id n = array3[array3.count-1]; 

您還可以循環數組更加快速簡潔這樣的:那麼,

NSNumber *n = [array3 lastObject]; 
NSLog(@"the last object is %@ or view it this way %d", n, [n intValue]); 

你也可以用這樣的新語法訪問數組

for (id object in array3) { 
    NSLog(@"%@", object); 
} 
+0

先生,謝謝你的工作正常.. – Nasir

+0

先生,什麼是「ID」是什麼意思? – Nasir

+0

一個id是一個objective-c關鍵字,它是'某種對象',參見http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html – Tim

0

它給你是一個垃圾值,因爲你試圖將一個對象轉換爲最可能的基元。

此外,for循環是不必要的。

n = [[array3 lastObject] integerValue];

應該是你所需要的一切。如果這仍然是垃圾,那是因爲數組中的對象是垃圾(或不能轉換爲整數)。在這一點上,看看你在哪裏設置array3。

+0

由於OP在他的'NSLog()'中使用'%d',我假設他使用'int'而不是'NSInteger',所以會調用'intValue'而不是'integetValue';) – HAS

相關問題