Where to place your typedef struct declaration file ?

Nibbie
Posts: 4
Joined: 2009.10
Post: #1
I just started playing with typedef struct

MyClass.h
Code:
#import <Cocoa/Cocoa.h>
@interface MyClass:NSObject
{
    NSRange Range;
}
-(void) Generic_Message;
@end

MyClass.m
Code:
#import "MyClass.h"
#import <stdio.h>
#import <Foundation/Foundation.h>

@implementation MyClass
-(void) Generic_Message
{
    //Range = { 17 , 4 }; //For some reason, this doesn't work :(
    Range=NSMakeRange (17,4) ;
    NSLog (@"\nRange location: %d\nlength: %d",  Range.location, Range.length );
}
@end

Main.m
Code:
#import "MyClass.m"

int main(int argc, char * argv[])
{
    id ClassInstance = [ [MyClass alloc] init];
    [ClassInstance Generic_Message];
    [ClassInstance release];
    return 0;
}

I have two questions, why doesn't
Code:
Range = { 17 , 4 };
work ?

And secondly, how to I create my own typedef struct ?
For example I created this:
Code:
typedef struct _CustomType
{
    int width;
    int length;
    int height;
}
CustomType;
where do I put it ?
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #2
Assigning using "{}" to a struct will only work if you're initializing an object. Therefore, it only works if you were to do this:
Code:
NSRange range = {17, 4};
To get around this problem, Apple provides some convenience functions to assign variables for their structures. In this case, use:
Code:
Range = NSMakeRange(17, 4);

You can declare your struct either in your header file if you want to use it everywhere, or in your .m file if you only need it in that file. It should be declared outside of any @implementation/@end or @interface/@end block.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  typedef struct - lossing data on some levels at random times jjslay 6 4,167 Jun 26, 2010 02:36 PM
Last Post: jjslay
  creating a struct in objective c kendric 12 18,686 Mar 10, 2009 03:36 PM
Last Post: Josh