1

How can I create NSMutableArray of Structures?

I can create an array of Structures in standard-c but am running into problems in objective-c.

standard-c:

struct person people[10];

thanks

2
  • 3
    I have seen a lot of your questions come up in the last 2 days or so, and it seems like they all have to do with kinda fighting the Objective-C way, and OOP in general.. the collection classes are your friends, people should be a class call People and it should be added to an NSArray or NSMutableArray. It will be so much easier to get memory management right. Commented Jul 13, 2011 at 20:18
  • 2
    I'd take it one step further; Don't use a structure at all. There is no reason why your person can't be a class Person (at least no reason as indicated by your questions so far). You are going down a path that is a complete waste of time, it seems. Commented Jul 13, 2011 at 20:58

1 Answer 1

3

You need to copy each struct into an NSData or NSValue object in order to place it in an NSArray.

// in
struct person someGuy = ...;
NSData *personData = [NSData dataWithBytes:&someGuy length:sizeof(struct person)];
[personArray addObject:personData];

// out
NSData *personData = [personArray objectAtIndex:whatever];
struct person someGuy;
[personData getBytes:&someGuy];

You should understand the difference between stack and heap and how to work with pointers (or be ready to learn), otherwise you will see a lot of EXC_BAD_ACCESS (or worse, no exceptions, just mysterious garbage data).

Sign up to request clarification or add additional context in comments.

4 Comments

Since it looks lot a lot of work to do Objective-c method for array of structures... is there any reason why I should not just implement standard-c convention for the structure or do I run the risk of the app crashing?
It's impossible to answer that without knowing more about your use case. But in general, I'd say don't mess with C structs unless you need them to interface with a C library that uses them.
@Suran STL containers are not available unless you are using Objective-C++, which you shouldn't be using unless you need to link your code with existing C++ code.
@benzado You're right..:-) But, in my case it was useful, and from a performance point of view, I think, in this case, using STL containers will be better...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.