Showing posts with label iPhone. Show all posts
Showing posts with label iPhone. Show all posts

Tuesday, May 3, 2016

Objective C Categories

Categories were introduced in Objective-C If we want to add any new functionalities to the native classes as well as to our own custom classes.

If the above statement is sounding new to you, Please check my 
Objective C Subclass vs Category post, Which gives a clear idea to you on when to subclass and when to categorize.

Let's see some cases where we have to go for Categories instead of Subclassing by taking NSString class.

I want string reversal at various places in my application.
I want number of spaces in a string.


In this case, We have two options.


                         



#1 Write a subclass of NSString and add these two methods.



   @interface MyString : NSString

     - (NSString*)reverseString;
     - (int)numberOfSpaces;

   @end


If I subclass and write my custom methods, 

I need to import that subclass header file wherever I need those methods.
And I need to instantiate my subclass everywhere to use those methods.



  MyString *str = [MyString alloc] init];

  NSString *reverseStr = [str reverseString];

  int numberOfSpaces = [str numberOfSpaces];


Isn't it painful for a matter of adding two new methods writing a sub class and using it?

What if there is something which allows us to add these two new methods in the scope of native class itself and allows us to call directly using NSString object.

Sounds great?

#2 Categories


In your Xcode editor, Go to,

 File -> New -> select 'Objective-C File' 

You will be getting,

File : Enter the category name of your choice. In my case it is 'Additions', as there are additions to NSString.
File Type : Category
Class : The base class for our categorization. In our case, It is NSString.

NSString+Additions.h and
NSString+Additions.m 

will get created in your project.

The file names them self convey the reason behind their creation. We have taken those files to add our custom functionality to the NSString class. So wherever we need those new custom methods, We need to import
NSString+Additions.h file.

Let's add our custom methods now.

NSString+Additions.h




  #import

  @interface NSString (Additions)

    - (NSString*)reverseString;
    - (int)numberOfSpaces;

  @end



Whatever the category name we have given in the File box, appears in the brackets.
Here, NSString (Additions). You can keep your own name. 


NSString+Additions.m 




 #import "NSString+Additions.h"

 @implementation NSString (Additions)

 - (NSString*)reverseString{
    
    NSMutableArray *strArr = [[NSMutableArray alloc] init];
    
    //taking all the characters of the string into an array
    
    for(int i=0;i<self.length;i++){
        
         char c = [self characterAtIndex:i];
         NSString *character = [NSString stringWithFormat:@"%c",c];
         [strArr addObject:character];
        
    }
    
    //forming a reverse string by looping the array starting from the last object
    
    NSMutableString *mstr = [[NSMutableString alloc] initWithString:@""];
    
     for(int i=strArr.count-1; i >= 0; i--){
          [mstr appendString:[strArr objectAtIndex:i]];
     }
    
     return [mstr copy];
    
 }

 - (int)numberOfSpaces{
    
     NSArray *strArr = [self componentsSeparatedByString:@" "];
     return strArr.count-1;
 }

 @end



They could be a better logic for string reversal.
Please ignore my logic for reversing a string though it's working :)




                         


We have added our required custom methods to the NSString class. Let's see how to access them.

Wherever you need these methods, import NSString+Additions.h file and you can access them as simple as the native NSString methods as shown in the below example.



    NSString *blogName = @"iOS Solves Blog";
    NSString *reverseName = [blogName reverseString];
    
    NSLog(@"reverseName : %@",reverseName);  // reverseName : golB sevloS SOi
    
    int numberOfSpaces = [blogName numberOfSpaces];
    

    NSLog(@"numberOfSpaces : %d",numberOfSpaces); //numberOfSpaces : 2


Hope this post is useful. Feel free to comment incase of any queries.

Thursday, April 28, 2016

Objective C Extensions

Before going to the topic, Let's see some real time scenarios we come across where we need this topic :)

I need a class property to be readonly to outside world but should be readwrite inside my class.
I need local variables but I don't want to expose them to outside of my class.

Let's discuss these requirements with a practical example in real time.


                         



I have a Employee class here having two properties.

  • salary
  • isTaxApplicable



     
#import

     @interface Employee: NSObject
      {

      }

        @property(nonatomic,assign) int salary;
        @property(nonatomic,readonly) BOOL isTaxApplicable;

        -(id)init;

    @end




#1 : I need a class property to be readonly to outside world but should be readwrite inside my class.


In Employee class, isTaxApplicable depends on salary value. Obviously I need to make isTaxApplicable property as readonly to outside world. Whereas, It should be readwrite inside my Employee class.

Here comes the concept called Extensions. In the implementation file (.m file) of the class, We can write the extension as shown below. 



  #import "Employee.h"

  @interface Employee ()

  @property(nonatomic,readonly) BOOL isTaxApplicable;

  @end


Here we can change the access level of a property. I have given the readonly access level in the header file and in the implementation, I have changed the access level to readwrite.

Now I can write isTaxApplicable property inside my class.

This is one of the uses of Extensions, Where we can change the access level of a property. Outside of this class can only read the property, they can write to it.


                         




#2 : I need local variables but I don't want to expose them to outside of my class.


We may need some temporary variables inside our class while implementing the business logic inside our class. But, we don't want them to be visible to outside world though they can't access it. In this case also, instead of keeping these temp variables in the header file, we can keep them in the extensions inside our implementation file as shown below.



  #import "Employee.h"

  @interface Employee () {

      int tempCounter;
      NSArray *tempArray;

  }

  @property(nonatomic,readonly) BOOL isTaxApplicable;

 @end


If you ask me,

why can't we keep them in the header file it self?

My answer is,

Let's say you are doing a static library where only header files in the library are visible. In this case keeping the temporary variables which outside of your class can't access doesn't look good. Why because, they don't need those. In fact they can't use those. So keeping those type of variables inside the extensions looks good and fine. Agree?


#3 : I need to go for a private API


If we want a method to be a private method, We can implement that in the implementation file so that It is not visible to outside world including the sub classes. For one or two methods it is fine. But, What If we have huge number of private methods?
If we implement all in the implementation file with out defining them any where, It is hard to know the private methods in the implementation file.

For this, We can create a private API using the Extensions. We can define all the private methods in the Extension of a class. If we don't implement these methods in the implementation file, Compiler will give a warning as well. Looking at the extension , We can see all the private methods inside a class. For one two methods, there is no need of this API, Where as for huge number of methods, It helps us a lot.



  #import "Employee.h"

  @interface Employee () 
   {

      int tempCounter;
      NSArray *tempArray;

   }

  @property(nonatomic,readonly) BOOL isTaxApplicable;

  /****   Private API   ******/

  -(void)privateMethod1;

  -(NSString*)privateMethod2;

  -(BOOL)privateMethod3:(int)val;

  @end



Hope this post is useful. Feel free to comment incase of any queries.

Sunday, April 3, 2016

Objective C Subclass vs Category

We all know what are sub classes. Whenever we take a ViewController or a control like Button or TextField, we see they are inherited from the respective parent classes as shown below.



  @interface MyViewController : UIViewController
  @interface MyButton : UIButton

  @interface MyTextField : UITextField


Then, What are categories?

If I want to add my own functionality, I mean some new methods which are not available in the parent class, I can write categories as shown below.



  
UIImage+ ImageAdditions.h
  @interface UIImage (ImageAdditions)


Have a look at my Objective-C Categories post to get clear idea on Categories.

Now, we know what are Subclasses and what are Categories.

Both are there to add some customized functionality. Then what is the difference between those two and where they fit exactly, I mean what is the scope of those.

When to Subclass:


When we need to override any existing functionality of a parent class, we need to go for Subclasses. For example, I want to override the 'didSelectRowAtIndexPath' method of UITableView, Whenever I use this sub class in my application, on selecting a row, I want to execute my custom functionality. In this case it is better to go for the Subclassing. Because you are just customizing the existing functionality, not writing any thing new here.



                         



When to Categorize:

When we need to add some new functionality to the existing class, we need to go for categories. For example, I want to add a method in UIImage class, Where calling it gives me a circular image. In this case, you don't have any thing for this in UIImage class, You are writing a new functionality to the UIImage class. So, here is the correct choice is Categories.


Hope this post is useful. Feel free to comment in case of any queries.

Friday, February 5, 2016

Objective C fetching device details

We can get device details on which our app is running using the UIDevice class in UIKit framework.

In this post let's see some of the needy details that we can get from this UIDevice class.

UIUserInterfaceIdiom


Though we have auto layouts, auto resizing to build user interface screens for iOS apps, some times we need to know whether our app is running on an iPad or on an iPhone. We can get the using UIUserInterfaceIdiom which is having two values.


  •     UIUserInterfaceIdiomPhone,          
  •     UIUserInterfaceIdiomPad


  if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){

       // App is running on iPad
  }

  else{

       // App is running on iPhone

  } 



name


We may need it occasionally. This is the device name that user has set in the device. If we need it to display the name of the device we can use this property to fetch as shown below.




    [UIDevice currentDevice] name]




systemVersion


It's is mandatory now a days to check the iOS version and program as per the new features along with taking deprecated things into consideration. We can fetch the device system version using the systemVersion property as shown below and write our customizations.




  if([[[UIDevice currentDevice] systemVersion] isEqualToString:@"7.0"]){


  }



orientation


Device orientation checking is very important if we are supporting all the orientations. We can fetch current orientation of the device using this orientation property which  gives one of the below listed values based on the device current orientation.




   [UIDevice currentDevice] orientation]




  •     UIDeviceOrientationUnknown,
  •     UIDeviceOrientationPortrait,  
  •     UIDeviceOrientationPortraitUpsideDown,  
  •     UIDeviceOrientationLandscapeLeft,       
  •     UIDeviceOrientationLandscapeRight,      
  •     UIDeviceOrientationFaceUp,              
  •     UIDeviceOrientationFaceDown            




batteryLevel


If our app is having background services like location or weather changes, it is a good practice to check the device battery level and handle the things. If the battery level is very low, better to stop these services for a while and alert the user about the battery state. We can fetch the battery level of the device using this batteryLevel property.

This value ranges from 0 - 1.0 and gives -1.0 if the battery state is unknown.


UIDeviceBatteryState


If we have a scenario like, we need to stop some activities in the app if the device is getting charged. This detail we can fetch using batteryState property. It gives one of below listed values.


  •     UIDeviceBatteryStateUnknown,
  •     UIDeviceBatteryStateUnplugged,     // on battery, discharging
  •     UIDeviceBatteryStateCharging,       // plugged in, less than 100%
  •     UIDeviceBatteryStateFull,        



Hope this post is useful. Feel free to comment in case of any queries.

Wednesday, February 3, 2016

Objective C Custom Fonts

In this post, Let's discuss on how to add custom fonts to our project and use them in our application.

Here are the sequence of steps to achieve this applying custom fonts.

1. Add your font files to the project.
2. Add those files from project to 'Copy Bundle Resources'.

TARGETS -> Build Phases -> Copy Bundle Resources

3. In the info.plist, in the 'Custom iOS Target Properties' section, add a key name 'Fonts provided by application'. In that key add items by mentioning all of your custom font names as the properties one by one. 

We have successfully added custom fonts to our project. The next step is the interesting step which is applying the custom fonts to our labels in the application.

4. Before applying, we need to know the exact name of the font to apply. For this, we need to do a single iteration of all the fonts to know the exact name of our custom font.



   
 for (NSString *familyName in [UIFont familyNames]) {

        for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {

            NSLog(@"%@", fontName);
        }

    }


The above loop will give you all the font names that available in the system to use in your project. As we have already added our custom fonts to our project, we can see those font names also in the log.


Hope this post is useful. Feel free to comment in case of any queries.

Wednesday, January 13, 2016

Objective C preparing JSON object



We all know that JSON is the most suitable format for to and fro of the data through mobile services. Because, It is light weight and the format is easy to read and write.

In this post let's discuss on how to prepare a JSON object from a list of information whether it's a key based information (NSDictionary) or a index based information (NSArray).

Let's say we have user profile information in a dictionary as shown below.

NSDictionary *userInfoDict = [NSDictionary alloc] initWithObjectsAndKeys:

@"Karunakar",@"firstname",
@"Bandikatla",@"lastname",
@"Male",@"gender",
@"India",@"country",
@"Degree",@"education",

nil];

We need to send the above information to a service. Obviously, we can't send a dictionary object to a service. We need to convert it to string format and on the server side this information should be parsable. So we need to convert it to a JSON string.

Let's see how to convert a dictionary information to a JSON string using Objective C.

Using NSJSONSerialization, we can convert this dictionary to NSData and then we can pass it to service or we can convert this to NSString from NSData and then pass it as a JSON formatted string as shown below.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject: userInfoDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

Sometimes, we may even need to upload user information or some other information as a file to the server. In this case we can directly give NSData to file upload service. We need to check the error value to make sure things are fine before sending it to the server.

Last but not the least, let's see what is that 'options' parameter here. If we are uploading this user info file to the server, If we open that file, If we want that file to be in a JSON readable format like shown below, the option should be NSJSONWritingPrettyPrinted. If you are not bothered about the pretty writing format, you can ignore that parameter.














Hope this post is useful. Feel free to comment incase of any queries.