Search code examples
objective-cfor-loopios6

iOS-values being printed NULL outside for loop,but prints well inside the for loop


I am posting the code which i have tried.

 .h file
    --------------
    @property (nonatomic,retain)  NSString *selectedChannelIDAlert;
    @property (nonatomic,retain)  NSString *pNewString;

    .m file
    -----------
    @synthesize selectedChannelIDAlert,pNewString;

    -(void)callfun{
    NSArray *jsonData=[NSJSONSerialization JSONObjectWithData:GETReply options:kNilOptions error:nil];
        selectedChannelIDAlert=[jsonData valueForKeyPath:@"items.snippet.resourceId.channelId"];

        for (pNewString in selectedChannelIDAlert) {

            NSLog(@"inside:%@",pNewString);

        }
    NSLog(@"outside:%@",pNewString);
    }

My output is
--------
2013-12-24 17:38:01.590 TubeAlert[1230:907] inside:UCK376qNDlNZZDNHsnaWuTeg
2013-12-24 17:38:01.892 TubeAlert[1230:907] inside:UC6Ju00QIPQw2mCcUSrbyQKQ
2013-12-24 17:38:02.200 TubeAlert[1230:907] inside:UCshoKvlZGZ20rVgazZp5vnQ
2013-12-24 17:38:02.750 TubeAlert[1230:907] inside:UCVzbLPpZ_VMqDzUtmN3uU9A
2013-12-24 17:38:03.429 TubeAlert[1230:907] inside:UCo0vVHI3Oz7O5zTc6f-5lgw
2013-12-24 17:38:03.735 TubeAlert[1230:907] inside:UCqg2eLFNUu3QN3dttNeOWkw
2013-12-24 17:38:04.144 TubeAlert[1230:907] inside:UCrYnLkVfvVf0Qy0YOUQdk2A
2013-12-24 17:38:04.574 TubeAlert[1230:907] inside:UCCOIC6NrBFrVCcI7tcXNWpQ
2013-12-24 17:38:04.966 TubeAlert[1230:907] inside:UCcMTZY1rFXO3Rj44D5VMyiw
2013-12-24 17:38:05.374 TubeAlert[1230:907] inside:UC-wwO4iPfQtoNjbS792Mpzg
2013-12-24 17:38:05.685 TubeAlert[1230:907] inside:UCrSi7xopc9-SWRMydSq5e1Q
2013-12-24 17:38:06.090 TubeAlert[1230:907] inside:UC-lHJZR3Gqxm24_Vd_AJ5Yw
2013-12-24 17:38:06.500 TubeAlert[1230:907] inside:UCEe076nFuVobN0bAsXK7ICw
2013-12-24 17:38:06.913 TubeAlert[1230:907] inside:UCgSHGbs2oGoLItc-8y5hJ9g
2013-12-24 17:38:07.318 TubeAlert[1230:907] inside:UC-LPIU24bQXVljUXivKEeRQ
2013-12-24 17:38:07.730 TubeAlert[1230:907] outside:(null)

So please tell me where I am going wrong ,so that I can get result printed both inside and outside the for loop.Thanks


Solution

  • It is never a good idea to use a property as a loop variable in a for-in loop.

    In your example, the value of the variable pNewString is controlled by the for-in loop, meaning that it is valid only inside the body of that loop. Once the loop has finished, accessing the value is not safe: fast enumeration that is used behind the scene to implement the for-in loop can set it to an arbitrary value, which appears to be nil for Cocoa's NSArrays.

    To avoid this issue in the future, consider declaring your pNewString variable in the loop's scope, like this:

    for (NSString * NSString in jsonData) {
        ...
    }
    

    If you would like to get the last value from the array, use

    NSLog(@"outside:%@", [jsonData lastObject]);