Reputation: 3095
I stored some strings in objects and added the objects to an NSMutableArray. Now I want to print the strings in each element of the array. Clearly, I'm doing something wrong. I'm going to back and review these basics, but I was hoping someone could explain how I can print the string instead of the what looks to be the element address.
/** interface **/
@property (nonatomic, copy) NSString*myNumber;
-(void)setNumber: (NSString*) randomNumber;
/** implementation **/
@synthesize myNumber;
-(void) setNumber:(NSString *)randomNumber
{
myNumber = randomNumber;
}
/**main**/
Fraction * aFrac = [[Fraction alloc] init];
[aFrac setNumber:@"5/6"];
Fraction * bFrac = [[Fraction alloc] init];
[bFrac setNumber:@"2/3"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
[myArray addObject:aFrac];
[myArray addObject:bFrac];
int i;
for(i = 0; i<2; ++i)
{
id myArrayElement = [myArray objectAtIndex:i];
NSLog(@"%@", myArrayElement);
}
for(i = 0; i<2; ++i)
{
NSLog(@"%@", myArray[i]);
}
Both for loops print the same thing.
Upvotes: 0
Views: 1735
Reputation: 7758
I'm guessing the Fraction
type you created has a NSString property or method named number (to match the -setNumber:
method), in which case you would use the following code to print it:
NSLog("%@", [myArrayElement number]);
Or, for the second loop:
NSLog("%@", [myArray[i] number]);
Upvotes: 1
Reputation: 15035
In your code both for loop meaning has same only, try below
for(i = 0; i<2; ++i)
{
id myArrayElement = [myArray objectAtIndex:i];
NSLog(@"%@", myArrayElement.number);
}
for(i = 0; i<2; ++i)
{
NSLog(@"%@", myArray[i].number);
}
Now here two array value you are extracting [myArray objectAtIndex:i] which is equivalent to myArray[i]
Upvotes: 0
Reputation: 71
When you pass a custom object to NSLog you have to override the -(NSString)description method in that object.
So in your Fraction class if you simply override this function like so
- (NSString*)description
{
return self.myNumber;
}
that should log out what you want.
I would probably think about renaming that property from number as you are storing a string.
Hope that helps
Upvotes: 2