September 4, 2010 0

What is a struct?

By admin in Uncategorized

So as i’ve learned more about programming in Objective-C, things that scared me at first are less scary now.
One thing I wondered and stayed away from at first were ‘Structs’ – because they sounded alien to me, I just didn’t get them.

In Objective-C, everything inherits from NSObject.
That’s a really great thing, you get a lot of awesome stuff like reference counting, @selectors, isaKindOf, conformsToProtocal, init constructors, dealloc.

However sometimes you don’t want all of that – you just want to store a couple of variables in a tiny object.
That’s where structs come into play, in fact you’re already familiar with them (CGPoint and and CGRect are structs, they are not NSObjects)

Structs are just containers for whatever properties you declared they can hold.

Here’s an example of creating one:

struct TimeInfo
{
	float elapsed;
	float duration;
};
typedef struct TimeInfo TimeInfo;
'

First I say struct then, it’s name, then i can go ahead and declare the data types it will contain.
The second part, ‘typedef struct…’ – If you didn’t do that you would have to say – struct TimeInfo everytime you wanted to use your object.

Here’s one in practice:

- (id) init
{
	self = [super init];
	if (self != nil)
	{	
                // Notice that there is no constructor for a struct
                _myTimeInfo.elapsed = 0.0f;
                _myTimeInfo.duration = 0.0f;
	}
	return self;
}

That’s all there is too them, and they’re super handy for when NSObject would be overkill

Tags:

Leave a Reply

Powered by WP Hashcash

Spam protection by WP Captcha-Free