Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Initializing C array of objects



On 20 Dec 07, at 02:58, Ken Tozier wrote:
I'm writing a class that needs to allocate a C array of objects and am having some trouble getting the things initialized. Here's what I'm doing but it's giving me "lvalue" errors
<snip>
(fooArray + i) = [foo init];

I'm not sure what exactly you're trying to accomplish here, but you can't assign a value ([foo init]) to the result of a calculation (fooArray + i). But that's kind of tangential to the actual problem...


How does one do something like this?

You can't. The Objective-C runtime depends on being able to manage memory for each object individually. In particular*, [NSObject alloc] calls malloc, and [NSObject dealloc] calls free(self) as its last action - trying to do this on a memory region that wasn't returned by malloc() will fail horribly.


*: This isn't necessarily exactly what the runtime is doing, but it's a reasonable facsimile. You shouldn't depend on these exact details being true, but you can (and should) take home the lesson that you can't do Cocoa's memory management for it.

Unless you're dealing with a very large number of very small objects, you're probably better off just using NSArray. The overhead is lower than you might imagine. If you *are* dealing with a lot of very small objects, or for some other reason NSArray isn't appropriate, you're just going to have to bite the bullet and store a bunch of structs instead.
_______________________________________________


Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden
References: 
 >Initializing C array of objects (From: Ken Tozier <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.