Coding under the Hammer
Objective-C
Retrieving the currently being played music track
Jul 11th
One question I keep hearing is “Can you find out what music track a user is listening to? as I want to use it for …”, where the reason usually revolves around posting it to a social network network site, or using it as IM status. Thankfully retrieving the currently being played music track is very easy thanks to the MediaPlayer Framework.
Each application has its own MPMusicPlayerController, but it also has access to the iPod’s MPMusicPlayerController, using the class method iPodMusicPlayer.
MPMusicPlayerController *iPodMusicPlayerController = [MPMusicPlayerController iPodMusicPlayer];
After you have got the iPod music player, you can then get the now playing item
MPMediaItem *nowPlayingItem = [iPodMusicPlayerController nowPlayingItem];
If the now playing item is nil, you know that the user is not playing a music track on their iPod.
Unlike many of the other APIs in iOS, you can’t access information such as the track name, via a simple string property. You have to use one of the following keys:
NSString *const MPMediaItemPropertyPersistentID;
NSString *const MPMediaItemPropertyMediaType;
NSString *const MPMediaItemPropertyTitle;
NSString *const MPMediaItemPropertyAlbumTitle;
NSString *const MPMediaItemPropertyArtist;
NSString *const MPMediaItemPropertyAlbumArtist;
NSString *const MPMediaItemPropertyGenre;
NSString *const MPMediaItemPropertyComposer;
NSString *const MPMediaItemPropertyPlaybackDuration;
NSString *const MPMediaItemPropertyAlbumTrackNumber;
NSString *const MPMediaItemPropertyAlbumTrackCount;
NSString *const MPMediaItemPropertyDiscNumber;
NSString *const MPMediaItemPropertyDiscCount;
NSString *const MPMediaItemPropertyArtwork;
NSString *const MPMediaItemPropertyLyrics;
NSString *const MPMediaItemPropertyIsCompilation;
NSString *const MPMediaItemPropertyReleaseDate;
NSString *const MPMediaItemPropertyBeatsPerMinute;
NSString *const MPMediaItemPropertyComments;
NSString *const MPMediaItemPropertyAssetURL;
And then query the Media Player Item, using the instance method valueForProperty:.
NSString *itemTitle = [nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];
And thus you will end up with a code snippet like this:
MPMusicPlayerController *iPodMusicPlayerController = [MPMusicPlayerController iPodMusicPlayer];
MPMediaItem *nowPlayingItem = [iPodMusicPlayerController nowPlayingItem];
if(nowPlayingItem)
{
NSString *itemTitle = [nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];
NSLog(@"User is playing the following song: %@",itemTitle);
}else {
NSLog(@"User is not playing a song");
}
As always this is just a small code snippet to get you started. There are situations for instance, where the user can have a now playing item that has no title (strange I know). So as always you will have to handle these edge cases appropriately.
MapKit
May 16th
Location, Location, Location is all the rage at the moment. Where did someone last update their social network status ? Where is the nearest restaurant ? Where do I need to be in 5 mins ? the possibilities for location services are (nearly) endless. But what is a location ? well put simple it is just a co-ordinate value (longitude and latitude), and in the case of iPhone, it is in reference to the earth. But lets be honest, displaying -122.03, 37.33 in your sexy new iPhone application is not very exciting now is it ? That is were MKMapView comes in.
MKMapView allows you to display a Map on your iPhone’s screen. MKMapView is just a subclass of UIView so you can treat it like one. You can ether use it as a subview (such as on a profile page), or make it go full screen (using it with its own view controller) such as when you are viewing a map to get directions.
So like UIView, to create a MKMapView you need to initialise one with a frame:
MKMapView *mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,0,320,480)];
Unlike UIView, you will also want to become the delegate of MKMapView.
mapView.delegate = self;
The delegate methods for MKMapView include ones that inform you about when the map starts and finishes to load, in addition to if it fails to load at all. (These delegate methods are very similar to UIWebView if you have used that).
- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView;
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView;
- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error;
In addition to the loading of the Map, the delegate also provides call backs for when the map’s region changes, it also provides callbacks regarding annotation information (more on that later).
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated;
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated;
After you have created a MKMapView, you will want to show a specific region on the map. The method to do this is:
- (void)setRegion:(MKCoordinateRegion)region animated:(BOOL)animated;
This introduces a new MapKit data type MKCoordinateRegion. This is the centre point (that you want to show) expressed as a co-ordinate, and then the distance (span) around this co-ordinate that you want to be shown. In essence the span is the zoom level. The bigger the span, the bigger the area that is displayed on the map.
To make a new region you will need to use:
MKCoordinateRegionMake(CLLocationCoordinate2D centerCoordinate, MKCoordinateSpan span);
And thus you will probably have some code that looks like this:
CLLocationCoordinate2D coordinate;
coordinate.latitude = -122.03;
coordinate.longitude = 37.33;
MKCoordinateSpan span = MKCoordinateSpanMake(0.003, 0.003);
[mapView setRegion:MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(0.003, 0.003)) animated:YES];
After you have focused in on a specific region of the map, you will more than likely want to annotate a given point. To do this you need to create an object that conforms to the (informal) MKAnnotation protocol, and in particular implements the CLLocationCoordinate2D coordinate property.
e.g.
@interface MCSMMapAnnotation : NSObject {
}
@property (nonatomic) CLLocationCoordinate2D coordinate;
@end
Then you just need to create an instance of this model object, and then add it to the map as an annotation:
MCSMMapAnnotation *annotation = [[MCSMMapAnnotation alloc] init];
CLLocationCoordinate2D annotationCoordinate;
coordinate.latitude = -122.03;
coordinate.longitude = 37.33;
annotation.coordinate = annotationCoordinate;
[self.mapView addAnnotation:annotation];
And that is it, nice and simple.
One more thing …
Before I mentioned that there are delegate methods regarding the annotations on the Map View. One that is particular useful is:
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)annotationViews;
Why is it useful ? Well if you didn’t notice, doing the above means that the annotation(s) just appear on the screen and they do not drop on. So in this delegate method, you can move the annotations off screen and then put them back to where MapKit said they should be.
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)annotationViews{
//The final (correct) position of the annotation
CGRect finalFrame;
//The position we will drop the annotation from
CGRect offScreenFrame;
for(UIView *annotationView in annotationViews) {
//MapKit has worked out the annotations final position so store it
finalFrame = annotationView.frame;
//We just want to move the annotation, so it is just above the top of the visible screen
offScreenFrame = CGRectMake(finalFrame.origin.x,(finalFrame.size.height *-1) , finalFrame.size.width, finalFrame.size.height);
//Set and therefore move the annotation to the off screen position
annotationView.frame = offScreenFrame;
//Set up an animation block to animate the drop
[UIView beginAnimations:@"AnimateAnnotation" context:NULL];
[UIView setAnimationDuration:1.0];
//Set the final frame, to be the frame that map kit originally calculated
annotationView.frame = finalFrame;
[UIView commitAnimations];
}
}
This is just a brief overview of what you can do with MapKit. The most obvious thing you can do, is to add more than one annotation to the map, and the above animation trick is designed to work with this. One feature you may want to do if your application heavily relies upon maps, is to create your own custom pins (that don’t even need to look like pins), to point out specific points on the map.
Redirecting NSLog to a log file
Dec 19th
Using NSLog is all well and good for debugging iPhone OS applications when the device is connected to your Mac, but what about when it is not. Often you want to give builds of your application to people that don’t have Xcode installed (or can’t get the silly certificates to work !!!), or just as commonly, to test if the application works outside of your lovely office which has a perfect WiFi connection.
When I first thought about this problem, I was thinking along the lines of build a custom log function lets say MagicLog() and this calls a function that saves the string to a file. The problem with this is that I would have to go through all of my code and add MagicLog() to everywhere that I have NSLog(), that seemed a bit to verbose for my liking.
After searching on the internet I found out that (rather obvious) NSLog runs over standard error. This means that you are able to simply redirect standard error to a file using the ANSI function freopen().
FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict stream);
http://www.opengroup.org/onlinepubs/000095399/functions/freopen.html
Before we can save NSLog() to a file, we first have to find a place to save it. The best place to do this is the application’s documents folder. To get this you can use the following code snippet:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
Once we have the documents folder, we need to give a name to the file. To make it easy for me I just name it “the date”.log :
NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
To make this into a valid path, use the NSString method stringByAppendingPathComponent
NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
The last step is to redirect stderr to this file
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
To keep my code maintainable I keep all of this as a function, and I call it in my AppDelegate if I want to turn this functionality on.
- (void)redirectNSLogToDocumentFolder{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]];
NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}
Getting the file.
Now that you have logged all the information you need, you will want to get this off of the device. Thankfully this is easy as well. Simply open the organiser in Xcode and select the device that is currently connected to your Mac.
A the bottom of the main pain there is an application section. Open the detail disclosure on the application you want to get the data from, and hit the little download button to the right of the Application Data package. You will be prompted to save this folder to your mac.
Warning:
Writing to the file system on the iPhone is slow, so this will effect the performance of your application. Therefore DO NOT ship an application with this in, or give it to people that can’t stand poor performance.
URL Encoding
Oct 25th
If you have tried to send any information using a GET web request, you would have come across an annoying problem. That annoying problem is making sure that the URL is correctly encoded.
At first glance it would seem that the Cocoa Frameworks do this for you, and you would be right …. well kind of.
The issue is that by default most of these methods leave characters such as & = ? within a URL, as they are strictly speaking valid. The problem is that these characters have special meanings in a GET request, and will more than likely make your request in valid.
Luckily there is a function in Core Foundation that helps:
CFStringRef CFURLCreateStringByAddingPercentEscapes (
CFAllocatorRef allocator,
CFStringRef originalString,
CFStringRef charactersToLeaveUnescaped,
CFStringRef legalURLCharactersToBeEscaped,
CFStringEncoding encoding
);
What makes this function useful, is the legalURLCharactersToBeEscaped parameter. This will escape legal characters such as & ? = if they are supplied. This allows you to escape parameters using the following code.
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)parameter, NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8)
An example of when to use this, is Twitters Update status API. You can find that here http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0update
To update your status to the following:
This is my status
You would need to post up the following URL:
http://twitter.com/statuses/update.xml?status=This%20is%20my%20status
As this is such a common problem of mine, I have created a category on NSURL. This allows you to pass in a base URL and a parameters dictionary.
+ (NSURL *)URLWithBaseString:(NSString *)baseString parameters:(NSDictionary *)parameters{
NSMutableString *urlString =[NSMutableString string];
//The URL starts with the base string
[urlString appendString:baseString];
NSString *escapedString;
NSInteger keyIndex = 0;
for (id key in parameters) {
//First Parameter needs to be prefixed with a ? and any other parameter needs to be prefixed with an &
if(keyIndex ==0)
{
escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);
[urlString appendFormat:@"?%@=%@",key,escapedString];
[escapedString release];
}else{
escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8);
[urlString appendFormat:@"&%@=%@",key,escapedString];
[escapedString release];
}
keyIndex++;
}
return [NSURL URLWithString:urlString];
}
Using a parameters dictionary keeps the code nice and clean, but beware, to use the category method above you still have to make sure that your keys, and the base URL are correctly encoded (no spaces or invalid characters !!!!!).
As we now have a category method to do all the hard work for us, to create the Twitter URL you just need to do the following:
NSString *baseString=@"http://twitter.com/statuses/update.xml";
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"This is my status",@"status",nil];
NSURL *url=[NSURL URLWithBaseString:baseString parameters:dictionary];
And thats it. Obviously this category can be used for things other than twitter ….. if you really want to.
Reopening an application’s main window by clicking on the Dock Icon
Aug 9th
When building Mac applications, Apple usually takes care of most of the default behaviours for you. One thing that Mac applications don’t do by default is, reopening the applications main window (if it has been closed), when the dock icon is pressed.
Although this information is very hard to find in the documentation, but is actually very easy to. The method you need to find is:
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag;
This is an optional delegate method that your AppDelegate can choose to implement, and is called when the user presses your application’s dock icon. The bool flags indicates whether the application has any visible windows. To reopen your application’s main window, you need to have a pointer to it (In the example below assume that it is defined as NSWindow *window; in the header file). If you do have a pointer to then you simple need to implement the code below.
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag{
if(flag==NO){
[window makeKeyAndOrderFront:self];
}
return YES;
}
It is as simple as that.
Simple UIView based Animations on the iPhone
Jul 18th
Although for complex animation sequences on the iPhone you need to use either the OpenGL or Apple’s very own Core Animation Framework, a lot of simple animations can be achieved with the methods found in the UIView class. All these animations are actually built upon Core Animation, but they have been wrapped up for you to use with very little code.
All animations triggered by the UIView class happen within a animation block.
To start an animation block you use the UIView Class method:
+ (void)beginAnimations:(NSString *)animationID context:(void *)context;
The animation ID is used in delegate call backs for such things as the beginning and end of animation blocks. The context is an additional piece of information that can be passed through.
As both of these parameters are optional, you comenly see:
[UIView beginAnimations:@"" context:NULL];
To commit these animations, and therefore end the animation block, you need to use the UIView class method:
+ (void)commitAnimations
So what types of animations can you do ? well quite a few.
You can animate views by:
- Changing their alpha
- Changing there size
- Changing there location
In a single animation block you can animate multiple views, and you are also able to nest animation blocks.
So lets do a common example. When a UITableViewCell is being edited you often want to make a UILabel’s (label) alpha change to 0 so it is hidden:
[UIView beginAnimations:@"" context:NULL];
[label setAlpha:(editing ? 0.0 : 1.0)];
[UIView commitAnimations];
For those new to C programming:
(editing ? 0.0 : 1.0)
Is equivlant to:
if(editing)
{
0.0;
}else{
1.0;
}
So for the second example we also have a UILabel (label), that we want to grow when the animation code is run. We also want this animation to last 2 seconds, so the user can admire our work. In addition to this, we want the animation to “ease in”. This is known as the animation curve. The animation curves that are available are
- ease in (slow then fast)
- ease out (fast then slow)
- ease in and out (slow, fast, slow)
- linear (constant speed)
We would do this animation using the following animation block:
[UIView beginAnimations:@"" context:NULL];
//The new frame size
[label setFrame: CGRectMake(0,0,320,100)];
//The animation duration
[UIView setAnimationDuration:2.0];
[UIView setAnimationDelay: UIViewAnimationCurveEaseIn];
[UIView commitAnimations];
This is just a brief overview of the animations you can do using the UIView class, but it should be enough to get you started. The UIView methods also include delegate call backs for when an animation starts and end. For more information see Apple’s Documentation.
If the UIView class does not have what you need, you will probably need to use the Core Animation framework. While using this framework is not trivial, it is not as hard as using OpenGL (which is used commonly for 3D games), and you can build some fantastic animations using it.
Helper Objects (Delegate and DataSource)
Jun 14th
Helper Objects are used throughout Cocoa and CocoaTouch, and usually take the form of a delegate or dataSource. They are commonly used to add functionality to an existing class without having to subclass it.
In software engineering, the delegation pattern is a technique where an object outwardly expresses certain behaviour but in reality delegates responsibility for implementing that behavior to an associated object in an Inversion of Responsibility. The delegation pattern is the fundamental abstraction that underpins composition (also referred to as aggregation), mixins and aspects.
http://en.wikipedia.org/wiki/Delegation_pattern
The most common use of helper objects in iPhone development is when using UITableViews. When you instantiate a UITableViewController this class is automatically assigned to be the delegate and dataSource of the table view it holds.
self.tableView.delegate=self;
self.tableView.dataSource=self;
The UITableView then calls the appropriate delegate method when it needs information, such as:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
This ask the delegate, what is the height for the row at a given index path, so in your UITableViewController (the delegate) you would write the following, if you wanted the row to be 44 pixels high (the default).
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 44;
}
Writing your own delegate.
Most delegates are declared as a protocol, so the compiler knows that the delegate implements the required methods.
Example:
You have created a subclass of UITextView (e.g. OBCTextView), that you use in your application to enter both Tweets and SMS. You want to use the same class for both, BUT tweets have a character limit of 140 and SMS have a character limit of 160 (we will pretend that we are still in the 90s).
So we need to create a delegate that asks for the character limit.
- (NSInteger) charachterLimitForTextView: (OBCTextView *)textView;
As mentioned before this should be declared as a protocol
@protocol OBCTextViewDelegate
- (NSInteger) charachterLimitForTextView: (OBCTextView *)textView;
@end
The OBCTextView would call this method like so:
-(void)askDelegateForCharachterLimit{
NSInterger charachterLimit = [delegate charachterLimitForTextView:self];
//Do something with character limit
}
In our SMS view controller we would declare that we implement the delegate protocol.
@interface OBCSMSViewController : UIViewController < OBCTextViewDelegate > {
}
@end
And then in the implementation file you would implement the following method
- (NSInteger) charchterLimitForTextView: (OBCTextView *)textView{
return 160;
}
This method is required for OBCTextView to work so we should also add the key word @required to the protocol
@protocol OBCTextViewDelegate
@required
- (NSInteger)charchterLimitForTextView:(OBCTextView *)textView;
@end
Optional methods
In your delegate, you may also want to implement optional methods. So for this example we will ask for the text color. You can specify that a method is optional using @optional.
@protocol OBCTextViewDelegate
@required
- (NSInteger)charachterLimitForTextView:(OBCTextView *)textView;
@optional
- (UIColor *)textViewColorForTextView:(OBCTextView *)textView;
@end
As it is optional the delegate class (helper object), does not have to implement it. If it does not implement it, and we attempt to call it, the application will crash. So how do we know if we should call the method or not ? The answer is respondsToSelector.
respondsToSelector allows you to ask an object at run time, if it implements a given selector. So for our example:
-(void)getTextColor{
if( [delegate respondsToSelector: @selector(textViewColorForTextView:)] ){
UIColor *textColor = [delegate textViewColorForTextView:self];
//Do something with the text color
}
}
if your class wants to return a textview color, then you simply implement the method.
- (NSInteger)textViewColorForTextView:(OBCTextView *)textView{
return [UIColor redColor];
}
So that finishes off this post on helper objects, and how you can create your own. As always this example was a simple one to make it easy to follow. You could probably implement the above using setter methods.
NSNumber: What is the point ?
May 31st
The first time you see NSNumber your probably say to yourself “What is the point of NSNumber? I already have int, float, double etc”. Although this may be true, there are many occasions when you actually need to use NSNumber.
1. Adding a number to an array
NSArray (NSMutableArray etc) does not allow you to add primitive types to it. This is because an NSArray is simple a set of pointers to the Objects you add to it. This means if you want to add a number to the array, you first have to wrap it in a NSNumber.
NSArray *numbers=[NSArray arrayWithObject:[NSNumber numberWithInteger:2]];
2. Number type conversion
NSNumber allows you to easily convert the type of a number e.g. from an int to a float
NSNumber *number=[NSNumber numberWithInteger:2];
float floatValue = [number floatValue];
3. Perform selector calls
Once you have used Objective-C for a while you may come across performSelector. This allows you to carry out advanced techniques like performing a selector after a given delay.
[magicObject performSelector:@selector(performMagicWithNumber:) withObject:[NSNumber numberWithInteger:2] afterDelay:1.0];
This the equivilant of doing the following without a delay:
[magicObject performMagicWithNumber: [NSNumber numberWithInteger:2] ];
4. Persisting Objects (CoreData)
Archiving Objects is a lot easier than archiving primitive types, as NSNumber inherits from NSObject you can use various archiving and de-archiving methods on them. CoreData actually requires you to use NSNumber for persistent storage. One thing that may not be obvious at first glance, is that CoreData (and Objective-C) considers BOOL as a NSNumber.
Summary:
You may write the best selling application on the Appstore and never use NSNumber, but if you need to persist your objects or you need access to the various performSelector calls, NSNumber is obviously the way to go.
Categories
May 22nd
Ever thought “Oh I wish Apple had included method X for class Y”, well that is what categories are for.
Categories are normally used for 2 things.
- Extending a class (using methods, not variables !!!)
- Logically separating a class into different functional areas
So lets look at something that is extremely popular at the moment ….. Twitter, and in paticular the 140 charachter limit.
Apple (for obvious reasons) don’t include Twitter related method calls on there string class NSString.
At the moment you would have to write everywhere in you code, something the resembles the following
NSString *twitterString=@"Objective-C rocks, I never want to look at Java again";
if([[twitterString] length]< 141)
{
//Post to twitter
}
Now this is good, but what if twitter changed their character limit, you would have to go an edit your code everywhere, where you used this check.
So we are going add a method to the NSString class:
-(BOOL)isUnderTwitterCharachterLimit;
This will make are code look like this
NSString *twitterString=@"Objective-C rocks, I never want to look at Java again";
if([twitterString isUnderTwitterCharachterLimit])
{
//Post to twitter
}
You now need an interface and implementation file, Im going to call them NSStringTwitterCategory.h and NSStringTwitterCategory.m
The interface file (NSStringTwitterCategory.h) is extremely small:
#import
@interface NSString (Twitter)
-(BOOL)isUnderTwitterCharachterLimit;
@end
Instead of defining a new class in the format:
@interface NewClass: SuperClass{
}
You extend an existing class using the format:
@interface ClassYourExtending (CategoryName)
You can call the category whatever you want, but obviously you want to make it clear.
You then declare the methods like you always do.
The implementation file (NSStringTwitterCategory.m) is also not very complex:
#import "NSStringTwitterCategory.h"
@implementation NSString (Twitter)
-(BOOL)isUnderTwitterCharachterLimit{
if ( [ [self length] <141])
return YES;
else
return NO;
}
@end
Again you extend the class in the same way as you did in the header file:
@implementation NSString (Twitter)
And you simple define the method as you normally would, nothing strange or fancy. If you want to use this category you just need to import the header file where you want to use it.
This is obviously a very simple example, but I hope it shows you how to use categories in Objective-C.
Does a NSString contain a substring ?
Apr 12th
Here is a little tip on how to tell if a string contains another string, using the underused data type NSRange.
NSRange gives the starting location and the length of a given value, and is often used with arrays and strings. On this occasion we will use it to find the range of a substring within another string. If the range has a location, it contains the given substring. The following code does just that.
NSRange textRange;
textRange =[string rangeOfString:substring];
if(textRange.location != NSNotFound)
{
//Does contain the substring
}
Making this a case insensitive compare is also very trivial, and can be done by lowercasing both strings
NSRange textRange;
textRange =[[string lowercaseString] rangeOfString:[substring lowercaseString]];
if(textRange.location != NSNotFound)
{
//Does contain the substring
}