1

Sorry about this silly question. I'm trying to learn objc and I'm unable to do a simple sum between 2 int values... In fact problem is before the sum.

I have an object that have an instance variable defined as a NSNumber and it's defined as a property as follows:

@interface MyObj : NSObject {
   NSNumber *count;
}
@property (readwrite, assign) NSNumber *count;
@end

@implementation MyObj
@synthetize count;
@end

Then I have a class that will consume MyObj:

- (void)total:(MyObj *)mobj {
   int count = [mobj.count intValue];

   NSLog(@"%@", mobj.count);
   NSLog(@"%@", count);

   int total = 10 + count;
   NSLog(@"%@", total);
}

The first NSLog prints the mobj.count nicely (let's say 5), but the second one, throws an EXC_BAD_ACCESS. And of course the program never reachs the sum.

So, what I'm doing wrong? I'm trying to convert it to a int based on this post.

TIA,

Bob

Community
  • 1
  • 1
Bob Rivers
  • 5,261
  • 6
  • 47
  • 59

5 Answers5

11

The specifier %@ is for printing Obj-C objects, and it asks for the object’s -description. The count in your code is an int. Use %i for ints. Check out NSLog() Specifiers.

Abizern
  • 146,289
  • 39
  • 203
  • 257
Evadne Wu
  • 3,190
  • 1
  • 25
  • 25
2

Another possible problem:

@property (readwrite, assign) NSNumber *count;

you most likely want to use retain so it won't disappear out from under you (as a rule of thumb: use assign for primitive types, retain for objects)

@property (readwrite, retain) NSNumber *count;
cobbal
  • 69,903
  • 20
  • 143
  • 156
1
NSLog(@"%@", count);

should be:

NSLog(@"%i", count);

because it's an int, not an object.

Also look at

NSLog(@"%@", total);

because its also not an object but an int

Jay
  • 4,480
  • 3
  • 25
  • 22
0
int count = [mobj.count intValue];

should be

count = [NSNumber numberWithInt:[mobj.count intValue]];

It shows there itself, count is a NSNumber, when you are trying to set it to an int.

Garrett
  • 7,830
  • 2
  • 41
  • 42
0

in your NSLog try:

NSLog(@"%@", [count stringValue]);
ennuikiller
  • 46,381
  • 14
  • 112
  • 137