Drew
Drew

Reputation: 153

get objects in NSMutableArray

assume the following:

@interface BOOK : NSObject
{
    @private
    NSString *title;
    NSString *author;
    NSString *ISBN;
}
...
BOOK *booklist = [[[BOOK alloc] init] autorelease];
NSMutableArray *myarray = [NSMutableArray array];
while (true)
{
    booklist.title = @"title";
    booklist.author = @"author";
    booklist.ISBN = @"1234-1";
    [myarray addObject:booklist];
}

my question is how do I retrieve object of BOOK i.e booklist.title, .author, .ISBN at a certain index in myarray.

Upvotes: 15

Views: 70179

Answers (4)

YanSte
YanSte

Reputation: 10839

You have this extends if you want

Create file extends.h add this code and #import "extends.h" in your project :

/*______________________________ Extends NSMutableArray ______________________________*/
/**
 * Extend NSMutableArray
 * By DaRkD0G
 */
@interface NSMutableArray (NSArrayAdd)
/**
 *  Get element at index
 *
 *  @param index
 */
- (NSObject *) getAt:(int) index;
@end
/**
 * Extend NSMutableArray Method
 * By DaRkD0G
 */
@implementation NSMutableArray (NSArrayAdd)
/**
 *  Get element at index
 *
 *  @param index
 */
- (NSObject *) getAt:(int) index {
    NSInteger anIndex = index;
    NSObject *object = [self objectAtIndex:anIndex];
    if (object == [NSNull null]) {
        return nil;
    } else {
        NSLog(@"OK found ");
        return object;
    }

}
@end
/*______________________________ Extends NSArray ______________________________*/
/**
 * Extend NSArray
 * By DaRkD0G
 */
@interface NSArray (NSArrayAdd)
/**
 *  Get element at index
 *
 *  @param index
 */
- (NSObject *) getAt:(int) index;
@end
/**
 * Extend NSArray Method
 * By DaRkD0G
 */
@implementation NSArray (NSArrayAdd)
/**
 *  Get element at index
 *
 *  @param index
 */
- (NSObject *) getAt:(int) index {
    NSInteger anIndex = index;
    NSObject *object = [self objectAtIndex:anIndex];
    if (object == [NSNull null]) {
        return nil;
    } else {
        NSLog(@"OK found ");
        return object;
    }

}
@end

USE :

NSObject object = [self.arrayItem getAt:0];
NSObject object2 = [self.arrayItem getAt:50];

Upvotes: 0

Andreas Ley
Andreas Ley

Reputation: 9335

Starting with Xcode 4.5 (and Clang 3.3), you may use Objective-C Literals:

Book *firstBookInArray = myArray[0];

Upvotes: 3

scottD
scottD

Reputation: 135

This may not help at all, but I remember having trouble when not casting while pulling objects out of arrays...

Book *aBook = (Book *)[myArray objectAtIndex: index];

It may help, may not...and I know this post is old, but maybe it'll help someone..

.scott

Upvotes: 2

Matthias Bauch
Matthias Bauch

Reputation: 90117

with this code? Impossible, because you add the same bookList for the rest of the time (until there is no more memory)

With code without infinite loops you would use

NSInteger index = 0;
Book *aBook = [myArray objectAtIndex:index];
NSString *title = aBook.title;

Upvotes: 34

Related Questions