0% found this document useful (0 votes)
38 views55 pages

Objective C

Objective-C, developed in the early 1980s by Brad Cox and Tom Love, combines C's efficiency with Smalltalk's object-oriented programming model. It gained prominence when adopted by NeXT and later became integral to Apple's ecosystem, although it has been largely supplanted by Swift in modern development. Despite this, Objective-C remains relevant for legacy applications and offers educational insights into object-oriented programming.

Uploaded by

yksl3461
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views55 pages

Objective C

Objective-C, developed in the early 1980s by Brad Cox and Tom Love, combines C's efficiency with Smalltalk's object-oriented programming model. It gained prominence when adopted by NeXT and later became integral to Apple's ecosystem, although it has been largely supplanted by Swift in modern development. Despite this, Objective-C remains relevant for legacy applications and offers educational insights into object-oriented programming.

Uploaded by

yksl3461
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

{

Objective C
//C with classes

Musa Yüksel

... }
01 { ..
History of Objective-C
// Let’s add classes to C

} ..
History of Objective-C
01 Origins
In the early 1980s two software engineers Brad Cox
and Tom Love were seeking to combine Smalltalk’s
OOP model with the efficiency of C. Their endeavor
led to the birth of Objective-C in 1983.
History of Objective-C
02 Development
Cox and Love’s vision for Objective-C was to shape it
into a high-level, object-oriented language with a
unique messaging system on top of the performance
and low-level control of C. Soon the language
attracted attention of other engineers too.
History of Objective-C
03 Adoption by NeXT
When Steve Jobs founded NeXT Computer, he
adopted Objective-C as the primary language for its
operating system, NeXTSTEP. This move brought
Objective-C into the mainstream and solidified its
position as a key player in the software development
landscape.
History of Objective-C
04 Objective-C and Apple
When Apple acquired NeXT and bringing Steve Jobs
back to the company, it also brought Objective-C into
Apple’s fold. Objective-C found a new home and
became the cornerstone of Apple’s development
ecosystem with powering Apple’s iconic products.
History of Objective-C
05 Modernization with Swift
When Objective-C began to show signs of age as the
demands of modern software development evolved.
In 2014, Apple introduced a new programming
language called Swift which offers a more concise
syntax, improved memory management, and
enhanced safety features.
History of Objective-C
06 Legacy and Influence
While Swift has become the preferred choice for
developers, Objective-C continues to play a vital role
in the Apple ecosystem. Its influence extends beyond
Apple, with concepts from Objective-C inspiring other
languages and frameworks like Cocoa.
What did it become today

{ Niche Applications Educational Value


Objective-C is still relevant, Objective-C offers insights
especially in legacy into the foundations of OOP
codebases and supporting and serving as a historical
applications rely on its
unique features.
reference for students and
developers. }
02 { ..
How to develop with
Objective-C
// Apple, just Apple, only Apple

} ..
Environment Setup in MacOS

As the integrated development


environment for Apple, Xcode is More detailed
the best choice alongside the information and
other editors. references are
shared in the
document
Compiling in Windows
1. Install a development environment like 2. Ensure that you select the option to
Cygwin or MinGW that includes GCC install Objective-C support during the
(GNU Compiler Collection). installation process.

3. Open a command prompt and navigate 4. Use the GCC compiler to compile your
to the directory containing your code. For example:
Objective-C file.

gcc -o output_file input_file.m -lobjc -lgnustep-base


Compiling in Linux
1. Install the GNUstep development
environment and compiler if not already sudo apt-get install gnustep gnustep-devel
installed. You can do this by running:

2. Navigate to the directory containing


your Objective-C file using the terminal.

3. Use the GCC compiler to compile your code, gcc -o output_file input_file.m -lobjc -lgnustep-base
similar to the Windows process:
03 { ..
Syntax Features of
Objective-C
// I wish that C has some awkward notations

} ..
Person.h

{ ..
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, strong) NSString
*name;
@property (nonatomic, assign) NSInteger age;
- (void)printInfo;
@end Objective-C separates
interfaces(.h) and
implementation(.m) files,
promoting clarity and
Person.m encapsulation like C and C+
#import "Person.h" +
@implementation Person
- (void)printInfo {
NSLog(@"Name: %@, Age: %ld", self.name,

} ..
(long)self.age);
}
@end
1.
Comment Lines

// This is a single-line comment


{ ..
/*
This is a
multi-line comment
*/
Objective-C supports both C-
style comments (/* */) and
C++-style comments (//).

} ..
2.
Data Types

NSString *staticString = @"Hello";


//Statically typed object of type NSString { ..
NSString *uppercased = [object uppercased];
/*
Compiler knows uppercaseString is a valid
method for NSString, so no error Objective C fully supports
*/ both the dynamic typing and
static typing features. It
inherits all data types from C
and also supports object
id object = @"Hello"; oriented typing.
// Dynamically typed object
NSString *uppercased = [object uppercased];

} ..
/*
Works even though the compiler doesn't know
the type of object at compile time
*/
3.
Objects

{ ..
// Creating an object
Class *object = [[ClassName alloc] init];

Objects in Objective-C are


instances of classes.

} ..
4.
Messaging

{ ..
// Sending a message to an object
id messageData = [object method:parameter];

Messaging is the primary


means of invoking methods
on objects.

} ..
5.
Methods

// Interface declaration
@interface ClassName : SuperClassName
{ ..
// Method declaration
-(returnType)method:
(parameterType)parameter;
@end
Objective-C methods are
defined within @interface
and @implementation
blocks.
// Implementation
@implementation ClassName
-(returnType)method:
(parameterType)parameter{

} ..
// Method implementation
}
@end
6.
Declaring Properties

// Interface declaration
@interface ClassName : SuperClassName
{ ..
// Method declaration
-(returnType)method:
(parameterType)parameter;
@end
Properties are declared
within the @interface
section using the @property
keyword, followed by the
desired attributes and the
// Implementation
@implementation ClassName
data type of the property.
-(returnType)method:
(parameterType)parameter{

} ..
// Method implementation
}
@end
7.
Synthesizing Properties

@implementation MyClass
@synthesize name = _name;
{ ..
/* Synthesizing property 'name' with
instance variable '_name' */
@synthesize age = _age;
/* Synthesizing property 'age' with instance
variable '_age' */ Accessor methods for
@end properties can be
synthesized manually using
@synthesize keyword

} ..
{ ..
Objective-C traditionally
uses manual memory
management with retain,
release, and autorelease
methods. However, with the
introduction of Automatic
Reference Counting (ARC),
memory management is
largely automated.

} ..
{ ..
Prior to ARC, developers had
to manually synthesize the
accessor methods. However,
with ARC, it's automatically
handled by the compiler.
Nonetheless, it's still
common to explicitly
synthesize properties for
clarity or to customize their
behavior.

} ..
8.
Accessing Accessors
MyClass *myObject = [[MyClass alloc] init];
// Using dot notation to set property values
myObject.name = @"John";
{ ..
myObject.age = 30;
// Using traditional method invocation to
Once properties are
get property values declared and synthesized,
NSLog(@"Name: %@", myObject.name);
NSLog(@"Age: %ld", myObject.age); they can be accessed using
dot notation
(object.property) or
traditional method
invocation ([object
property]).

} ..
{ ..
Properties allow for
customization of getter and
setter methods, such as
implementing custom logic
or side effects. This can be
achieved by declaring
methods with specific names
(getter, setter) or by
overriding the default
behavior using @synthesize.

} ..
@interface Temperature : NSObject @implementation Temperature

@property (nonatomic, assign) float @synthesize celsiusTemperature =


celsiusTemperature; _celsiusTemperature;

@end -(void)setCelsiusTemperature:
(float)celsiusTemperature {
_celsiusTemperature = celsiusTemperature;
}

-(float)celsiusTemperature {
return _celsiusTemperature;
}
Temperature *temp = [[Temperature alloc] init];
temp.celsiusTemperature = 25.0; -(float)fahrenheitTemperature {
NSLog(@"Temperature in Celsius: %.1f°C", return (_celsiusTemperature * 9 / 5) +
temp.celsiusTemperature); 32;
NSLog(@"Temperature in Fahrenheit: %.1f°F", }
[temp fahrenheitTemperature]);
@end
9.
Protocols
// Protocol declaration
@protocol ProtocolName<NSObject>
- (void)methodName;
{ ..
@end
// Class conforming to protocol
@interface ClassName :
SuperClassName<ProtocolName>
// Class implementation
Protocols define a set of
@end methods that a class can
choose to implement. They
are declared using the
@protocol keyword.

} ..
10.
Categories

{ ..
// Category declaration
@interface ClassName (CategoryName)
-(void)methodName;
@end
// Implementation
@implementation ClassName (CategoryName)
-(void)methodName {
}
// Method implementation Categories allow you to add
@end
methods to existing classes
without subclassing them.

} ..
11.
Blocks

// Block declaration
ReturnType (^blockName)(ParameterTypes) =
{ ..
^(Parameters) {
// Block implementation
};
// Using a block
blockName(arguments);
Objective-C supports blocks,
which are similar to closures
in other languages.

} ..
12.
Exception Handling

@try {
// Code that might throw an exception
{ ..
}
@catch (ExceptionType *exception) {
// Code to handle the exception
}
@finally {
// Code that executes in any case
} Objective-C uses @try,
@catch, and @finally for
exception handling.

} ..
{ ..
Check the documentation if
you are interested in
objective-c and developing
applications for Apple
devices.

} ..
04 { ..
Commonly Used Libraries in
Objective-c

} ..
#import <Foundation/Foundation.h>
{ ..
int main(int argc, const char* argv[]) {
@autoreleasepool {
// insert code here…
NSLog(@"Hello, World!");
The Objective-C
}
programming language is
}
return 0;
based on C. All Objective-C
programming is done with
the Foundation library.

} ..
1.
UIKit

{ ..
UIKit is a framework provided by Apple for building
user interfaces in iOS, macOS, tvOS, and watchOS
applications. It includes classes for managing views,
controls, animations, and user interactions. UIKit is
essential for creating visually appealing and
responsive user interfaces.

} ..
2.
Core Data

{ ..
Core Data is a framework provided by Apple for
managing the model layer objects in an application.
It provides an object-oriented API for working with
data and supports features such as data persistence,
data modeling, and data validation. Core Data is
commonly used for implementing database
functionality in iOS and macOS applications.

} ..
3.
Core Graphics

{ ..
Core Graphics (Quartz 2D) is a framework provided
by Apple for rendering 2D graphics in iOS and macOS
applications. It includes classes and functions for
drawing shapes, images, text, and gradients, as well
as for performing transformations and compositing.
Core Graphics is often used for custom drawing and
rendering tasks in applications.

} ..
4.
AFNetworking

{ ..
AFNetworking is a popular third-party library for
handling network requests in Objective-C
applications. It provides an easy-to-use API for
making HTTP requests, handling responses, and
managing network operations asynchronously.
AFNetworking simplifies tasks such as downloading
data from a server, uploading files, and interacting
with RESTful APIs.

} ..
5.
SDWebImage

{ ..
SDWebImage is a widely used library for
asynchronous image loading and caching in
Objective-C applications. It provides a UIImageView
category that allows developers to easily set an
image from a URL and automatically handle caching,
downloading, and displaying of images. SDWebImage
improves the performance and responsiveness of
applications that display a large number of images.

} ..
6.
MagicalRecord

{ ..
MagicalRecord is a convenience library built on top of
Core Data that simplifies common Core Data tasks
and reduces boilerplate code. It provides a set of
helper methods and conventions for managing Core
Data entities, contexts, and fetch requests.
MagicalRecord makes it easier to work with Core
Data and speeds up development by providing a
higher level of abstraction.

} ..
7.
Masonry

{ ..
Masonry is a lightweight layout framework for
building Auto Layout constraints in Objective-C
applications. It provides a fluent API for creating
constraints programmatically, which makes it easier
to define complex layouts and adapt to different
screen sizes. Masonry simplifies Auto Layout code
and improves readability by using a more expressive
syntax.

} ..
05 { ..
Commonly Used Functions
in Objective-c

} ..
1.
NSString Functions

● stringWithFormat: Creates an NSString object by formatting a string


with variable arguments.

● length: Returns the number of characters in an NSString.

● isEqualToString: Compares two NSString objects for equality.

● substringToIndex: Returns a substring from the beginning of an


NSString up to a specified index.
2.
NSArray Functions

● count: Returns the number of objects in an NSArray.

● objectAtIndex: Returns the object at a specified index in an NSArray.

● containsObject: Checks whether an object is present in an NSArray.

● sortedArrayUsingSelector: Returns a new NSArray sorted using a


specified selector.
3.
NSDictionary Functions

● count: Returns the number of key-value pairs in an NSDictionary.

● objectForKey: Returns the value associated with a specified key in


an NSDictionary.

● allKeys: Returns an NSArray containing all the keys in an


NSDictionary.

● removeObjectForKey: Removes the key-value pair with a specified


key from an NSDictionary.
4.
Memory Management Functions

● alloc: Allocates memory for an object.

● init: Initializes an object after memory allocation.


06 { ..
Some Example Codes
// Thank you AI

} ..
1.
User Story

{ ..
As a bank customer, I want to be able to deposit and
withdraw money from my account, with the balance
displayed in both USD and EUR.

} ..
@implementation BankAccount {
float _balanceInUSD; // Instance variable
@interface BankAccount : NSObject for balance in USD
}
@property (nonatomic, assign) float balance; //
Account balance in USD
@synthesize balance = _balanceInUSD;
@end
// Custom setter method to set balance in USD
- (void)setBalance:(float)balance {
_balanceInUSD = balance;
}

// Custom getter method to get balance in USD


- (float)balance {
return _balanceInUSD;
}

// Method to convert balance to EUR


- (float)balanceInEUR {
return _balanceInUSD * 0.85; // Assuming
1 USD = 0.85 EUR
}
@end
2.
User Story

{ ..
As a content creator, I want to be able to reverse the
text of a string to create intriguing content.

} ..
@interface NSString (StringManipulation)

// Method to reverse the text of a string @implementation NSString (StringManipulation)


- (NSString *)reversedString;
// Method to reverse the text
@end - (NSString *)reversedString {
NSMutableString *result = [NSMutableString
stringWithCapacity:[self length]];
for (NSUInteger i=[self length]; i>0; i--) {
[result appendFormat:@"%C",
[self characterAtIndex:i-1]];
}
return result;
}

@end
3.
User Story

{ ..
As a data analyst, I want to sort an array of numbers
in descending order to identify trends more easily.

} ..
NSArray *numbers = @[ @10, @5, @20, @15 ];

/*
Sorting array of numbers in descending order using blocks
*/

NSArray *sortedNumbers =
[numbers sortedArrayUsingComparator:

^NSComparisonResult(id obj1, id obj2) {


if ([obj1 integerValue] < [obj2 integerValue]) {
return NSOrderedDescending;
// obj1 should appear after obj2
} else if ([obj1 integerValue] > [obj2 integerValue]) {
return NSOrderedAscending;
// obj1 should appear before obj2
}
return NSOrderedSame;
// obj1 and obj2 are equal
}];

NSLog(@"Sorted Numbers: %@", sortedNumbers);


{ ..
"Technology is nothing. What's important is that you
have faith in people, that they're basically good and
smart, and if you give them tools, they'll do
wonderful things with them."

-Steve Jobs

} ..
Resources
● Official Document by Apple
● ARC in Swift Documents
● Medium Article About Objective-C
● Syntax Resource
● Functions Explanation from GeeksForGeeks
● Data Types Explanation from GeeksForGeeks
● Closures(Blocks) Explanation from Steemit
● And Ai Chat Bots Like ChatGPT

You might also like