Showing posts with label ObjectiveC. Show all posts
Showing posts with label ObjectiveC. Show all posts

Saturday, June 27, 2015

Attempt to mutate immutable object with appendString - ObjectiveC


"Attempt to mutate immutable object with appendString" is one of the most common error while doing iOS development. This will occur due to mutability of the NSString. Lets check in detail.
As most of you know foundation framework has two types of strings

  • NSString (not modifiable)
  • NSMutableString (can modify)

Basing on these strings, we can have below two scenarios.

1. We can assign NSMutableString to NSString
2. We can't assign NSString to NSMutableString

Scenario #1 is perfectly valid, because NSMutableString is a subclass of NSString. But scenario #2 will crash the application and throws below error message.

"Attempt to mutate immutable object with appendString"


To avoid this problem , while doing #2, you need to make mutableCopy to make a mutable string and assign. Check below for sample code.

 
 //Immutable string , cant modify
 NSString *firstName = @"Pasumarthi";
 //mutable string can modify
 NSMutableString *nameString = [NSMutableString stringWithString:@"Chandu"];
 
 // invalid - trying to make mutable string to non-mutable string 
 //nameString = firstName;
 //invalid - we cant make normal string copy to the mutable.
 //nameString = [firstName copy]; 
 
 // valid as mutablestring is subclass of string
 nameString = [firstName mutableCopy]; 
 
 // valid as mutablestring is subclass of string 
 firstName = nameString;
 //valid as nameString is mutable 
 [nameString appendString:@" Appu"];

Happy Coding!!!

Saturday, October 25, 2014

Difference between objectForKey and valueForKey in iOS

You may get this doubt when you work with NSDictionary in iOS. When you use these methods on Dictionaries, there wont be any much difference between objectForKey and valueForKey in iOS. Both methods behaves almost same on dictionaries. But valueForKey used on Key Value Coding (KVC ) as its a key value method.

Where to use: objectForKeywill work on NSDictionaries and valueForKey will work on NSDictionaries and KVC. On NSDictionaries both returns null if key not found. And valueForKey throws valueForUndefinedKey: exception on KVC if property not found. Check the examples below for more clarity.

Usage on NSDictionary: We can use objectForKey: and valueForKey: on dictionaries. Below is the sample code.

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"king",@"name",@"9985396338",@"phone", nil];
 // using objectForKey method
 NSLog(@"name is %@", [dict objectForKey:@"name"]);
 // displays null as name1 not found in NSDictionary
 NSLog(@"name1 is %@", [dict objectForKey:@"name1"]);
 // using valueForKey method 
 NSLog(@"phone is %@", [dict valueForKey:@"phone"]);
 // displays null as phone1 not found in NSDictionary
 NSLog(@"phone is %@", [dict valueForKey:@"phone1"]);

Usage on KVC: we can't use objectForKey: method on key-value coding. We can use valueForKey: method. Below is the example

// .h file
@interface valueForKeyTest : NSObject
@property NSString *name,*phone;
@end
// .m file
@implementation valueForKeyTest
@synthesize name, phone;
@end
// main.m file
#import "valueForKeyTest.h"
int main(int argc, const char * argv[]) {
 valueForKeyTest *obj = [[valueForKeyTest alloc] init];
 obj.name = @"king";
 obj.phone = @"9985396338";
 
 // valueForKey on accessor methods
 NSLog(@"name is %@", [obj valueForKey:@"name"]);
 NSLog(@"phone is %@", [obj valueForKey:@"phone"]);
 // this will throw valueForUndefinedKey: as name1 is not a property
 NSLog(@"name is %@", [obj valueForKey:@"name1"]);
}


Key Value Coding: A key is unique value, which identifies the property value of the object. A key generally accessor method or instance variable in the object, Check KVC for more info. KVC has below key value methods.


  • setValue:forKey:
  • valueForKey:
  • setValue:forKeyPath:
  • valueForKeyPath:
  • setValuesForKeysWithDictionary:
  • dictionaryWithValuesForKeys:


Thursday, March 28, 2013

iPhone developement slides


Here are the slide for the iOS development topics
  1. Introduction to iOS
  2. Views in iOS
  3. ViewControllers
  4. StoryBoards
  5. Notifications n KeyPadHiding
  6. Gestures
  7. CustomeGestures
  8. ViewHeirarchy, ResponderChain
  9. iOSArchitecture
  10. DataPersistence
  11. SQLite3
  12. CoreData
  13. XML n JSONParsing
  14. Communicating with WebServices
  15. AudioVideo Foundation
  16. Camera, Accelorometer
  17. Memory Crash issues
  18. UIPageViewController
  19. AutoLayout, iCloud
Download from this link.



Thursday, March 21, 2013

ObjectiveC slides

Here are the slides for the ObjectivC topics which given below.
  1. Introductin to ObjectiveC
  2. Objects, Classes, Messages in ObjectiveC
  3. OOPS concepts in ObjectiveC
  4. Properties in ObjectiveC
  5. protocols n Categories in ObjectiveC
  6. Selectors in ObjectiveC
  7. FoundationClasses in ObjectiveC
  8. NSString n NSNumber in ObjectiveC
  9. NSArray n NSData in ObjectiveC
  10. Dictionary, Range, Date in ObjectiveC
  11. NSFileManager, NSFileHandle in ObjectiveC
  12. Memory Management in ObjectiveC
  13. Blocks and GCD
Download slides from here.


Friday, November 23, 2012

private method objective C


In objectiveC, privilege levels are allowed for only data variables and not for methods. So public, private and protect access specifiers are valid for only data variables. But there is a feature called Category which is used for declaring private methods in objectiveC.

Using category we can implement private methods. But we need to declare the methods in .m file and not in .h file.So declaration and definition will be in the same source file.

Syntax for the private method:
//need to add both in .m file
@interface className (categoryName)
//new methods
@end
@implementation className (categoryName)
//new method definitions
@end
Example for private method: In this example, we add one private method to the NSObject class using category and its name is display which is enclosed in the braces.
@interface NSObject (display)
-(void) privateDisplay;
@end
@implementation NSObject (display)
-(void) privateDisplay
{
 printf("This is private display\n");
}
@end
//This class is declared in the .h file 
//and inherited from NSObject
@implementation categoryClass
@end

Wednesday, November 21, 2012

objective c categories

Categories is another good feature in ObjectiveC. A category is used to add the new methods to the existing class, even if you don't have source code of the class. Category only adds methods and not variables. The basic difference between category and extending the class is that, in extending the class you can additional methods and variables. But in category only methods are allowed.

A category is also used to declare the private methods.ObjectiveC provides security to only data variables and not for methods. So we can have public, protect and private access privileges to only data. Using category we can implement private methods. But we need to declare the methods in .m file and not in .h file.

Key points on Category:
  • Used to add the new methods to the exiting class and not variables
  • Used to create the private methods in objectiveC
  • No keyword is used for declaring category. Only enclosed in braces(see the syntax).
  • You can take as many catefories as you want, but they should be unique.

Syntax for the Category: There is no keyword for the declaration of the category. We need to enclose in the braces '(' and ')';
//.h file
@interface className (categoryName)
//new methods
@end
//.m file
@implementation className (categoryName)
//new method definitions
@end
Example for adding methods: In this example we add display method to the NSObject. We we have written two implementations, one is for NSObject new method and one is for new class.

// this is .h file
@interface NSObject (print)
-(void) display;
@end
@interface categoryClass : NSObject
@end
//this is in .m file
@implementation NSObject (print)
-(void) display
{
 NSLog(@"this is display function");
}
@end
@implementation categoryClass
@end
int main()
{
 categoryClass *obj = [[categoryClass alloc] init];
 [obj display];
}
Labels:

Monday, November 19, 2012

objective c @class

In Objective C @class is used for forward declaration. It tells the compiler that there’s a class of that name. we can use it in the interface declarations.

Lets see the sample code below.
@interface example : NSObject
{
 //compiler dont know where this class located
 forwardDemo *obj;
}
@end
@interface forwardDemo : NSObject
{
 //data
}
@end

In the above sample code, we have a interface example, data variable to that interface is object of another interface forwardDemo. But example interface dont know the declaration/existance of the forwardDemo interface, this is because example is declared before forwardDemo interface. To overcome this problem, we need to use the forward declaration. In objective C which is achieved by using @class keyword. Solution for the above is given below.
//forward declaration
@class forwardDemo;
@interface example : NSObject
{
 forwardDemo *obj;
}
@end
@interface forwardDemo : NSObject
{
 //data
}
@end


Labels:

Saturday, November 17, 2012

objective c protocol

Objective-C doesn't support multiple inheritance. So each class should have only one parent class. It should not have multiple parent classes for the derived class. But Objective-C supports a feature called protocol to implement multiple inheritance.

A protocol is a list of method declarations. And if you want use those methods , you need to write the implementation for those methods.

A protocol feature in objective-C is similar to interface in Java and pure virtual function in C++.

Syntax of the protocol declaration: you need to enclose the protocol in < and > when using it.
@protocol protocolName 
//new methods
@end
//class name and protocol names separated by spaces
@interface className : parentClass <protocolName>
//class methods
@end


Example for the protocol in Objective-C:
// these are in .h file
@protocol player 
-(void) bowling;
-(void) batting;
-(void) fielding;
@end
@interface cricketPlayer : NSObject <player>
-(void) display;
@end
// this is in .m file
@implementation cricketPlayer
-(void) display
{
 NSLog(@"this is display function");
}
-(void)batting
{
 NSLog(@"this is batting");
}
-(void)bowling
{
 NSLog(@"this is bowling");
}
-(void)fielding
{
 NSLog(@"this is fielding");
}
@end
int main(int argc, const char * argv[])
{
 
 cricketPlayer *obj = [[cricketPlayer alloc] init];
 [obj display];
 [obj batting];
 [obj fielding];
 return 0;
}
From the above example protocol with name player have three methods batting, bowling and fielding. We have created a new class called cricketPlayer whos parent class is NSObject and it uses the player protocol. So cricketPlayer's object is able to use all the methods which are available in the protocol. So now object has the properties of NSObject and protocol methods as well.

This way you can implement multiple inheritance using protocol.

Labels:

Thursday, September 6, 2012

Common Objective-C error!!


Recently I started learning Objective-C for my new project. Whatever the errors I am getting while compiling, I am sharing here, so that it will be helpfull to others. For Installing Objective-C in windows, see this post. Below are the some of the common errors you may face while compiling Objective-C program in winodws.

$gcc `gnustep-config --objc-flags` -L /GNUstep/System/Library/Libraries hello.m -o hello -lgnustep-base -lobjc
sh: gcc: command not found 
you may get above error, because system unable to get the gcc path. For this, we need to install devel part in GNUstep installation process (It contains three parts System, Core and devel). The devel binary sets the gcc compilar path, if you forgot to install the devel, you may see above problem.

$ gcc 'gnustep-config --objc-flags' -L /GNUstep/System/Library/Libraries hello.m -o hello -lgnustep-base -lobjc
gcc.exe: error: gnustep-config --objc-flags: No such file or directory
you may get this error, because instead of back-tick(`), you used single quotes(') in the gcc command for gnustep-config parameter.

$ gcc -L /GNUstep/System/Library/Libraries hello.m -o hello -lgnustep-base -lobjc
hello.m:1:34: fatal error: Foundation/Foundation.h: No such file or directory compilation terminated
you may get the above error, becaus you have not specified the path for the Foundation.h file. we need to specify gnustep-config flag to find the path for the Foundation.h file.

$ gcc `gnustep-config --objc-flags` -L /GNUstep/System/Library/Libraries hello.m -o hello
C:\Users\CPASUM~1\AppData\Local\Temp\ccifGII6.o:hello.m:(.data+0x0): undefined reference to `__objc_class_name_NSConstantString'
C:\Users\CPASUM~1\AppData\Local\Temp\ccifGII6.o:hello.m:(.data+0x4): undefined reference to `__objc_class_name_NSAutoreleasePool'
AppData\Local\Temp\ccifGII6.o: In function `main':
hello.m:5: undefined reference to `objc_get_class'
hello.m:5: undefined reference to `objc_msg_lookup'
hello.m:5: undefined reference to `objc_msg_lookup'
hello.m:7: undefined reference to `_imp__NSLog'
hello.m:8: undefined reference to `objc_msg_lookup'
ccifGII6.o: In function `_objc_gnu_init':
hello.m:10: undefined reference to `__objc_exec_class'
collect2: ld returned 1 exit status
you may get the above error, because you not specified the library of the objectiveC. This is similar to specifying the math library when you use mathematical functions like sqrt library functions.


$ gcc `gnustep-config --objc-flags` hello.m -o hello -lgnustep-base -lobjc
c:/gnustep/bin/../lib/gcc/mingw32/4.6.1/../../../../mingw32/bin/ld.exe: cannot find -lgnustep-base
c:/gnustep/bin/../lib/gcc/mingw32/4.6.1/../../../../mingw32/bin/ld.exe: cannot find -lobjc
collect2: ld returned 1 exit status
you may get the above error, becaus you have not specified the gcc library. you need to specify this library becaus , GNUstep runs on MinGW.

These are the some of the common errors. I will update this, whenever I got new errors.

Labels:

Wednesday, September 5, 2012

objective c compiler for windows

We can install the Objective-C compiler on windows platform using GNUstep. GNUstep is a free and open version of cocoa API's and tools for different platforms. GNUstep environment can be made in windows using a toolkit MinGW. MinGW stands for Minimal GNU for Windows. And it is a GNU compiler collection which includes Ojective-C compiler as well. GNUstep package itself contains MinGW package, so there is no need to install MinGW package.

Installation of GNUstep:
  • Download the windows installation package which includes three System, Core and Dev exe files from official website.
  • Install the packages System, Core and Dev in order.
And thats it, you have done the GNUstep environment in your system. To run the Objective-C program/application, go to Programs->GNUStep and there you can find Shell, just click on Shell you will get the Comman Line Interface. This shell is based on MinGW package. So you can able to compile the Objective-C applications/programs from this shell.

Compiling and running Objective C program on Windows: Create the HelloWorld program with below code in any text editor.
#import <Foundation/Foundation.h> 
int main (int argc, const char * argv[])
{
 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 NSLog (@"Hello World!");
 [pool drain];
 return 0;
}
save the file as hello.m and go to the shell and the compile the file with following command.
gcc `gnustep-config --objc-flags` -L /GNUstep/System/Library/Libraries 
hello.m -o hello -lgnustep-base -lobjc
If every thing goes fine, it will generate hello.exe file, because we specified the object file name as hello. If we are not using -o option, it will create a.exe file which is similar to a.out file. To execute the program, run the below command from the shell.
$ ./hello.exe
2012年09月05日 11:57:49.615 hello[1168] Hello World!

Click here for what are the possible errors with gcc for objective-C and why.

Labels:
Subscribe to: Posts (Atom)

Popular Posts

AltStyle によって変換されたページ (->オリジナル) /