int variable is not getting assigned??

Discussion in 'iOS Programming' started by AbhishekApple, Aug 27, 2010.

  1. AbhishekApple macrumors member

    Aug 5, 2010
    i have declared int variable totRecint as global but it is not getting assigned with value
    (showing garbage memory location)????

    but the string variable totRecstr gets a value from the array

    @implementation SearchViewController
    NSString *totRecstr;
    int totRecint;
    - (void)requestFinished:(ASIHTTPRequest *)request
    NSArray *arryPage = [[request responseString] componentsSeparatedByString:@","];
    		totRecint = (int)[arryPage objectAtIndex:0];
    		totRecstr = [arryPage objectAtIndex:0];
  2. Cromulent macrumors 603


    Oct 2, 2006
    The Land of Hope and Glory
    What is the type of the object stored in the array at index 0? The cast to int looks suspicious.
  3. Guiyon macrumors 6502a

    Mar 19, 2008
    North Shore, MA
    You can't do that. ints are primitives, not objects and therefore cannot be stored inside an NSArray without a wrapper (ie: NSNumber). What you are doing here is setting totRecint to the value of the pointer at index 0. You need to convert the returned value to an int first before you can perform the assignment. Hint: look at the "Getting Numeric Values" section in the NSString documentation.

    Edit: Mixed up NSInteger and NSNumber, need more coffee. Thanks ranguvar
  4. ranguvar macrumors 6502

    Sep 18, 2009
    NSInteger is not an object. NSNumber is.
  5. fluxforge macrumors member

    Apr 16, 2010

    [arryPage objectAtIndex:0];
    returns you a pointer to an NSObject. if you cast this pointer to int you will get the memory address the pointer points to written into the int variable. that's why you see "garbage" values in your int variable;

    do this instead:

    totRecint = [[arryPage objectAtIndex:0] intValue];
  6. rrichar macrumors newbie

    Aug 13, 2010
    Assuming your variable is Counter:

    1.) in your .h file put the following

    int counter;

    2.) in the .m file put the following code in the viewdidload IBACTION

    in counter = 0;
  7. AbhishekApple thread starter macrumors member

    Aug 5, 2010
    Thanks to all for not only giving the answer but also explaining why?

Share This Page