• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Splitting a string and assigning to variables
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Splitting a string and assigning to variables


  • Subject: Re: Splitting a string and assigning to variables
  • From: Shawn Erickson <email@hidden>
  • Date: Sun, 13 Jul 2003 16:13:59 -0700

On Sunday, July 13, 2003, at 02:30 PM, Jonathan Jackel wrote:

On Sunday, July 13, 2003, at 04:00 PM, Matt Diephouse wrote:

Book *newBook = [[Book alloc] init];
NSArray *parts = [bookInfo componentsSeperatedByString:", "];
[newBook setTitle: [parts objectAtIndex:0]];
[newBook setAuthor: [parts objectAtIndex:1]];
[newBook setPublisher: [parts objectAtIndex: 2]];

I think that's a bit ugly though. I hope there's a better way. Is there? Thanks.

The ugliness is the result of your data (bookInfo = @"Timeline, Michael Crichton, Knopf") being ugly. If your data started as a dictionary you could do this a little more elegantly. Arrays and strings don't know as much about their contents as dictionaries. OTOH, dictionaries take some effort to make in the first place.

Exactly what do you mean by "ugly" and "better" anyway?

One could implement things this way (assuming book info is always as you outlined above).

In your normal code...
...
Book* newBook = [Book bookWithStringDescription:bookInfo];
...


In your Book class...
#define kTitleIndex 0
#define kAuthorIndex 1
#define kPublisherIndex 2

+ (id) bookWithStringDescription:(NSString*)description
{
return [[[Book alloc] initWithStringDescription:description] autorelease];
}

- (id) initWithStringDescription: (NSString*)description
{
... using the recommend init pattern ...
NSArray *parts = [bookInfo componentsSeperatedByString:", "];
[newBook setTitle:[parts objectAtIndex:kTitleIndex]];
[newBook setAuthor:[parts objectAtIndex:kAuthorIndex]];
[newBook setPublisher:[parts objectAtIndex:kPublisherIndex]];
...
}

Of course you could operate on an array instead of a string or better yet a dictionary as suggested above with well defined keys for the values you are looking for.

-Shawn
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

References: 
 >Re: Splitting a string and assigning to variables (From: Jonathan Jackel <email@hidden>)

  • Prev by Date: Re: Splitting a string and assigning to variables
  • Next by Date: styled menu item?
  • Previous by thread: Re: Splitting a string and assigning to variables
  • Next by thread: About a bug in Jaguar
  • Index(es):
    • Date
    • Thread