Objective-C Typedef

Typedef is a keyword, used in giving a new name for a data type in Objective-C.

Here is an example to define a term BYTE for one-byte numbers:

typedef unsigned char BYTE;

After this type definition, the identifier BYTE now can be used as an abbreviation for the type unsigned char. Here is an example to use BYTE as unsigned char:

BYTE  bt1, bt2;

You can also use the keyword typedef to give a name to the user-defined data type in Objective-C also. Below is an example program illustrates this concept in Objective-C

Objective-C Typedef Example

You are free to use typedef with structure to define a new data type and then use that data type to define the structure variables directly like this:

/* Objective-C Typedef - Example Program */
#import <Foundation/Foundation.h>

typedef struct BOOKS
	NSString *title;
	NSString *author;
	NSString *subject;
	int bookid;

int main()

	Book book;
	book.title = @"Objective-C Typedef Tutorial";
	book.author = @"codescracker";
	book.subject = @"Objective-C Programming Tutorial";
	book.book_id = 100;
	NSLog( @"Book Title = %@\n", book.title);
	NSLog( @"Book Author = %@\n", book.author);
	NSLog( @"Book Subject = %@\n", book.subject);
	NSLog( @"Book ID = %d\n", book.bookid);
	return 0;

When the above code is compile and executed, it will produce the following result:

2014-10-03 13:18:37.932 demo[31183] Book Title = Objective-C Typedef Tutorial
2014-10-03 13:18:37.932 demo[31183] Book Author = codescracker
2014-10-03 13:18:37.932 demo[31183] Book Subject = Objective-C Programming Tutorial
2014-10-03 13:18:37.932 demo[31183] Book ID = 100

typedef and #define

The #define is an Objective-C preprocessor directive, which is also used to define the aliases for the various data types similar to the typedef but with these differences:

typedef #define
The typedef interpretation is performed by the compiler The #define statements are processed by the Objective-C preprocessor
The typedef is limited to giving symbolic names to types only The #define can be used to define alias for the values as well. For example, you can defined 3 as THREE

To learn more about #define, then refer Objective-C Preprocessors.

Objective-C Online Test

« Previous Tutorial Next Tutorial »