- A variable in an application consists of four components:
- Name
- Location (where it's stored in memory)
- Type (which kind of data it can store)
- Current Value
- Variables can store into 2 main types: Basic data type & Pointer.
<<Data Types>>
- Primitive data types:
Data Type | Storage Size | Group |
char | 1 byte | Character |
unsigned char ? | 1 byte | |
signed char ? | 1 byte | |
int / unsigned int | 2 or 4 bytes | Integer, by default, signed |
short / unsigned short | 2 bytes | |
long / unsigned long | 4 bytes | |
float | 4 bytes | Floating-point number, always signed; 6 decimal places |
double | 8 bytes | 15 decimal places |
BOOL | Boolean value | |
id | One special basic data type |
To get the exact size of a type or a variable, you can use the sizeof(type) operator:
#import <Foundation/Foundation.h>
int main()
{
NSLog(@"Storage size for int : %d \n", sizeof(int));
NSLog(@"Storage size for int : %d \n", sizeof(int)); return 0; } |
After compilation, the result will be shown as below:
2013-10-25 10:19:41.257 HelloWorld[1257:c07] Storage size for int: 4 2013-10-25 10:19:41.259 HelloWorld[1257:c07] Storage size for float: 4 |
_Bool b = 35; BOOL a = true; BOOL b = YES; BOOL c = 0; BOOL.BOOL in Objective-C |
char b = '2'; |
int c = 2; float aFloat; <-- // float are 4 bytes double d = 2.0; <-- // double are 8 bytes double d = 9.32e+12; long long double aLongDouble; <-- // long double are 16 bytes NSLog(@"%i,i); NSLog(@"%f,f); NSLog(@"%e,d); NSLog(@"%e,d); NSLog(@"%c,c); |
unsigned int a; signed int b; <-- by default |
* Notes:
- In Objective-C, int is the default data type for variables and
parameters. This means you can remove the keyword int from your variable
declaration statement and,
in most cases, it will still compile. Therefore, the following two variable declarations are equivalent:
unsigned a; unsigned int a; |
- As you explore Cocoa Touch, you’ll find that most APIs use data types with names such as NSInteger or NSUInteger instead of int and unsigned int. These additional types are part of Apple’s progress toward 64-bit computing.
<<int and float Conversion>>
int i = 20.86; <-- // chop off decimal part float f = 3/2; <-- // f = 1.000000; float f = 3.0/2; <-- // f = 1.500000; |
<<Type Casting>>
float f = (float) 3/2; <-- // f = 1.500000 int i = (int) 30.22; <-- // f = 30 i +=5; <-- // i = i + 5 |
<<id>>
- In Objective-C a variable, which can represent an object, makes use of a data type called id.
id name = @"Christopher Fairbairn"; |
- id is a special kind of data type in that it can store a reference to an object of any type.
NSString *name = @"Christopher Fairbain"; |
- Here the id data type is replaced by NSString *.
No comments:
Post a Comment