user3166940
user3166940

Reputation: 27

How do I synthesize Objective-C string?

I am trying to synthesize two strings in Objective C so the setter/getter is automatically created.

In my implementation:

#import "Song.h"

@implementation Song

@synthesize song, track;

@end

In my interface:

#import <Foundation/Foundation.h>

@interface Song : NSObject

@property string song, track;

@end

The error I am getting in my interface file is "Unknown type name string".

The error I am getting in my implementation file is "Expected a property name in @synthesize".

I am unsure what to do because I did this for int and it works.

Upvotes: 0

Views: 635

Answers (4)

JuJoDi
JuJoDi

Reputation: 14975

Synthesizing is done automatically in XCode 4.4 and later.

Your actual issue, though, is the declaration of the string properties.

in your header try

@property (strong, nonatomic) NSString *song;
@property (strong, nonatomic) NSString *track;

You can then reference those properties using

self.song

or access the property directly using

_song

Please note the second method is NOT recommended unless you're accessing the instance of the property within the setter or getter

The reason why it worked for int is because int is a primitive (and objective-c is a superset of C). An NSString is an NSObject in Objective-C and you must hold a strong or weak reference to it (you must point to it). You can read Apple's reference on encapsulating data for more information on properties.

Upvotes: 3

Sandeep Agrawal
Sandeep Agrawal

Reputation: 425

In implementation:

#import "Song.h"

@implementation Song

@synthesize song, track;

@end

In interface:

#import <Foundation/Foundation.h>

@interface Song : NSObject

@property (nonatomic, strong)NSString *song;
@property (nonatomic, strong)NSString *track;

@end

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

There are several problems in your code:

  • Cocoa does not have a type called string, you need to use NSString instead
  • As of Xcode 4.4 you do not need to use @synthesize.

Here is how:

@interface Song : NSObject
// Below I am using copy to avoid referencing potentially mutable strings.
// You may or may not want to use this approach.
@property (nonatomic, copy) NSString *song;
@property (nonatomic, copy) NSString *track;

@end

Upvotes: 5

Abhineet Prasad
Abhineet Prasad

Reputation: 1271

@property(nonatomic,strong) NSString *song;
@property(nonatomic,strong) NSString *track;

Upvotes: 0

Related Questions