Posts Tagged ‘Objective-C’
04
ott

Getting the Length of a String

The length of the string in a string object can be obtained by accessing the length method of the string object:

1
2
3
NSString *string1 = @"This string is Immutable";
int len = [string1 length];
NSLog (@"String length is %i", len);

Searching for a Substring

A common requirement when working with strings is to identify whether a particular sequence of characters appears within a string. This can be achieved using the rangeOfString method. This method returns a structure of type NSRange. The NSRange structure contains a location value providing the index into the string of the matched substring and a length value indicating the length of the match.

1
2
3
4
5
NSString *string1 = @"The quick brown fox jumped";
NSRange match;
match = [string1 rangeOfString: @"brown fox"];
NSLog (@"match found at index %i", match.location);
NSLog (@"match length = %i", match.length);

The NSLog call will display the location and length of the match. Note that the location is an index into the string where the match started and that the index considers the first position in a string to be 0 and not 1. As such, the location in our example will be 10 and the length will be 9.

In the event that no match is found, the rangeOfString method will set the location member of the NSRange structure to NSNotFound. For example:

1
2
3
4
5
6
7
NSString *string1 = @"The quick brown fox jumped";
NSRange match;
match = [string1 rangeOfString: @"brown dog"];
if (match.location == NSNotFound)
  NSLog (@"Match not found");
else
  NSLog (@"match found at index %i", match.location);

Replacing Parts of a String

Sections of a mutable string may be replaced by other character sequences using the replaceCharactersInRange method. This method directly modifies the string object on which the method is called so only works on mutable string objects.

This method requires two arguments. The first argument is an NSRange structure consisting of the location of the first character and the total number of characters to be replaced. The second argument is the replacement string. An NSRange structure can be created by calling NSMakeRange and passing though the location and length values as arguments. For example, to replace the word “fox” with “squirrel” in our sample mutable string object we would write the following Objective-C code:

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 replaceCharactersInRange: NSMakeRange(16, 3) withString: @"squirrel"];
NSLog (@"string1 = %@", string1);

As you may have noted from the above example, the replacement string does not have to be the same length as the range being replaced. The string object and replacement method will resize the string automatically.

String Search and Replace

Previously we have covered how to perform a search in a string and how to replace a subsection of a string using the rangeOfString and replaceCharactersInRange methods respectively. The fact that both of these methods use the NSRange structure enables us to combine the two methods to perform a search and replace. In the following example, we use rangeOfString to provide us with an NSRange structure for the substring to be replace and then pass this through to replaceCharactersInRange to perform the replacement:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 replaceCharactersInRange: [string1 rangeOfString: @"brown fox"] withString: @"black dog"];

When executed, string1 will contain the string “The quick black dog jumped”.

Deleting Sections of a String

Similar techniques to those described above can be used to delete a subsection of a string using the deleteCharactersInRange method. As with the preceding examples, this method accepts an NSRange structure as an argument and can be combined with the rangeOfString method to perform a search and delete:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 deleteCharactersInRange: [string1 rangeOfString: @"jumped"]];

Extracting a Subsection of a String

A subsection of a string can be extracted using the substringWithRange method. The range is specified using an NSRange structure and the extracted substring is returned in the form of an NSString object:

1
2
3
4
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;
string2 = [string1 substringWithRange: NSMakeRange (4, 5)];
NSLog (@"string2 = %@", string2);

When executed, the above code will output the substring assigned to string2 (“quick”).

Alternatively, a substring may be extracted from a given index until the end of the string using the subStringFromIndex method. For example:

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;
string2 = [string1 substringFromIndex: 4];

Similarly, the subStringToIndex may be used to extract a substring from the beginning of the source string up until a specified character index into the string.

Inserting Text into a String

The insertString method inserts a substring into a string object and takes as arguments the NSString object from which the new string is to inserted and the index location into the target string where the insertion is to be performed:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 insertString: @"agile, " atIndex: 4];

Appending Text to the End of a String

Text can be appended to the end of an existing string object using the appendString method. This method directly modifies the string object on which the method is called and as such is only available for mutable string objects.

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 appendString: @" over the lazy dog"];
NSLog (@"string1 = %@", string1);

Comparing Strings

String objects cannot be compared using the equality (==) operator. The reason for this is that any attempt to perform a comparison this way will simply compare whether the two string objects are located at the same memory location. Let’s take a look at this via an example:

1
2
3
4
5
6
NSString *string1 = @"My String";
NSString *string2 = @"My String";
if (string1 == string2)
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

In the above code excerpt, string1 and string2 are pointers to two different string objects both of which contain the same character strings. If we compare them using the equality operator, however, we will get a “Strings do not match” result. This is because the if (string1 == string2) test is asking whether the pointers point to the same memory location. Since string1 and string2 point to entirely different objects the answer, obviously, is no.

We can now take this a step further and change the code so that both string1 and string2 point to the same string object:

1
2
3
4
5
6
7
NSString *string1 = @"My String";
NSString *string2;
string2 = string1;
if (string1 == string2)
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

Now when we run the code, we get a “Strings match” result because both variables are pointing to the same object in memory.

To truly compare the actual strings contained within two string objects we must use the isEqualToString method:

1
2
3
4
5
6
NSString *string1 = @"My String";
NSString *string2 = @"My String 2";
if ([string1 isEqualToString: string2])
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

Another option is to use the compare method (to perform a case sensitive comparison) or the caseInsenstiveCompare NSString methods. These are more advanced comparison methods that can be useful when sorting strings into order.

Checking for String Prefixes and Suffixes

A string object can be tested to identify whether the string begins or ends with a particular sequence of characters (otherwise known as prefixes and suffixes). This is achieved using the hasPrefix and hasSuffix methods respectively, both of which return boolean values based on whether a match is found or not.

1
2
3
4
5
6
7
8
9
NSString *string1 = @"The quick brown fox jumped";
BOOL result;
result = [string1 hasPrefix: @"The"];
if (result)
  NSLog (@"String begins with The");

result = [string1 hasSuffix: @"dog"];
if (result)
NSLog (@"String ends with dog");

Converting to Upper or Lower Case

The Foundation NSString classes provide a variety of methods for modifying different aspects of case within a string. Note that each of these methods returns a new string object reflecting the change, leaving the original string object unchanged.

1
capitalizedString

Returns a copy of the specified string with the first letter of each word capitalized and all other characters in lower case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 capitalizedString];

The above code will return a string object containing the string “The Quick Brown Fox Jumped” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

1
lowercaseString

Returns a copy of the specified string with all characters in lower case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 lowercaseString];

The above code will return a string object containing the string “the quick brown fox jumped” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

1
uppercaseString

Returns a copy of the specified string with all characters in upper case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 uppercaseString];

The above code will return a string object containing the string “THE QUICK BROWN FOX JUMPED” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

Converting Strings to Numbers

String objects can be converted to a variety of number types:

Convert String to int

1
2
3
NSString *string1 = @"10";
int myInt = [string1 intValue];
NSLog (@"%i", myInt);

Convert String to double

1
2
3
NSString *string1 = @"10.1092";
double myDouble = [string1 doubleValue];
NSLog (@"%f", myDouble);


Convert String to float

1
2
3
NSString *string1 = @"10.1092";
float myFloat = [string1 floatValue];
NSLog (@"%f", myFloat);

Convert String to NSInteger

1
2
3
NSString *string1 = @"10";
NSInteger myInteger = [string1 integerValue];
NSLog (@"%li", myInteger);

Converting a String Object to ASCII

The string contained within a string object can be extracted and converted to an ASCII C style character string using the UTF8String method. For example:

1
2
3
NSString *string1 = @"The quick browen fox";
const char *utfString = [string1 UTF8String];
printf ("Converted string = %s\n", utfString);

Rif: http://www.techotopia.com
Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , , , , , , , , , , , , , ,

14
mar

Today a little tutorial to find a word in a big ordered text file using binary search in objective-c.





What is binary search? (Wikipedia -> http://en.wikipedia.org/wiki/Binary_search_algorithm)

A binary search or half-interval search algorithm locates the position of an item in a sorted array. Binary search works by comparing an input value to the middle element of the array. The comparison determines whether the element equals the input, less than the input or greater. When the element being compared to equals the input the search stops and typically returns the position of the element. If the element is not equal to the input then a comparison is made to determine whether the input is less than or greater than the element. Depending on which it is the algorithm then starts over but only searching the top or bottom subset of the array’s elements. If the input is not located within the array the algorithm will usually output a unique value indicating this. Binary search algorithms typically halve the number of items to check with each successive iteration, thus locating the given item (or determining its absence) in logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.


How to do it in Objective-C language?

First of all you need a text file containing a word on each line like this snippet:

[...]
vuotato
vuotava
vuotavamo
vuotavano
vuotavate
[...]

You need to read all file and save each line in an array.





Snippet in Objecitve-C using C stdlib

1
#include <stdlib .h>
1
2
3
4
5
6
7
8
9
10
  char buffer[512];
  NSMutableArray *mySortedArray = [NSMutableArray array];
  int charsRead = 512;
  do {
    if(fscanf(file, "%s\n", buffer, &charsRead) == 1)
      [mySortedArray addObject:[NSString stringWithFormat:@"%s", buffer]];
    else
      break;
  } while(charsRead == 512);
  fclose(file);

Once you’ve getted all lines, you can use

1
CFArrayBSearchValues

to make a binary search in your array.
Very easy yo use.

You don’t understand this snippet?
Here the full version of binary search in objective-c.
Continue reading “[Objective-C] Fast String Binary Search” »

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , , ,

10
gen

Hi all,
with these lines of code you can use Apple iOS Mail system to send an email with an attachment!





It’s so easy that i don’t know this method!

First, import MessageUI framework, after include in your header file (.h) the import to the framework:

1
#import messageui/MessageUI.h

and set the delegate to

1
mfmailcomposeviewcontrollerdelegate

Now, create a button in your view and attach mailil function!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult: (MFMailComposeResult)result error:(NSError*)error {
 [self dismissModalViewControllerAnimated:YES];
}

- (IBAction) mailIt {
 MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
 picker.mailComposeDelegate = self;
 
 [picker setSubject:@"This is the subject"];
 
 UIImage *roboPic = [UIImage imageNamed:@"anImage.jpg"];
 NSData *imageData = UIImageJPEGRepresentation(roboPic, 1);
 [picker addAttachmentData:imageData mimeType:@"image/jpg" fileName:@"anImage.jpg"];
 
 NSString *emailBody = @"This is the email body!!";
 [picker setMessageBody:emailBody isHTML:YES];
 
 [self presentModalViewController:picker animated:YES];
 [picker release];
}

done!





Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

06
ott

Yesssss!

it’s only a preview, i’m working on… but it works! It’s in objective-c.

Bing Map on iPhone

Bing Maps on iPhone!

Stay tuned….






Bing reference: http://www.microsoft.com/maps/isdk/ajax/
Rif: http://www.albertopasca.it/




FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , ,

02
ago

Do you want to create an UIColor from RGB value?

Here the snipplet:

1
2
3
4
#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

to use:

1
UIColor aColor = UIColorFromRGB(0xFF00FF);

it’s all!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , ,

23
lug

Bene, semplifichiamoci la vita.
Ecco come fare un parser di un xml in modo facile e veloce in pochi passi!

ReverseGeo.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#import <foundation /Foundation.h>

@interface ReverseGeo : NSObject {
       /* dichiarazioni */
  NSXMLParser   *revParser;
  NSMutableDictionary *item;
  NSString      *currentElement;
 
       /* Array contenenti i valori trovati nell'xml */
  NSMutableArray    *elements;
  NSMutableString   *citta,
            *via,
            *dug;
}
- (void) parseXMLFileAtURL: (NSString *) URL;
@end

ReverseGeo.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#import "ReverseGeo.h"

@implementation ReverseGeo
- (void) parseXMLFileAtURL: (NSString *) URL {
 
  @try{
    elements = [[NSMutableArray alloc] init];
    NSURL *xmlURL = [[NSURL alloc] initWithString:URL];
   
    revParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
   
    [revParser setDelegate:self];
    [revParser setShouldProcessNamespaces:NO];
    [revParser setShouldReportNamespacePrefixes:NO];
    [revParser setShouldResolveExternalEntities:NO];
    [revParser parse]
   
  }@catch (NSException * e) { }
}

- (void) parserDidStartDocument: (NSXMLParser *) parser { }

- (void) parser: (NSXMLParser *) parser parseErrorOccurred: (NSError *) parseError {
     NSLog(@"Errore nel parser!");
}

- (void) parser: (NSXMLParser *) parser didStartElement: (NSString *) elementName
                                                              namespaceURI: (NSString *) namespaceURI
                                                              qualifiedName: (NSString *) qName
                                                                     attributes: (NSDictionary *) attributeDict{

  currentElement = [elementName copy];
        /* tag xml di partenza */
  if ([elementName isEqualToString:@"RevGeo_Out"])
  {
    item    = [[NSMutableDictionary alloc] init];
    citta   = [[NSMutableString alloc] init];
    via   = [[NSMutableString alloc] init];
    dug   = [[NSMutableString alloc] init];
  }
}

- (void) parser: (NSXMLParser *) parser didEndElement: (NSString *) elementName
                                                             namespaceURI: (NSString *) namespaceURI
                                                             qualifiedName: (NSString *) qName{  
 
  if ([elementName isEqualToString:@"RevGeo_Out"])
  {
                /* riempio gli array con le chiavi */
    [item setObject:citta forKey:@"citta"];
    [item setObject:via forKey:@"via"];
    [item setObject:via forKey:@"dug"];

    [elements addObject:[item copy]];  
  }
}

- (void) parser: (NSXMLParser *) parser foundCharacters: (NSString *) string{
  @try {
                /* prendo i tag xml seguenti */
    if ([currentElement isEqualToString:@"com"]) {
      [citta appendString:string];
    } else if ([currentElement isEqualToString:@"topo"]) {
      [via appendString:string];
    } else if ([currentElement isEqualToString:@"dug"]) {
      [dug appendString:string];
    }
  }@catch (NSException *e) { }
}

- (void) parserDidEndDocument: (NSXMLParser *)parser { }

- (void) dealloc {  [super dealloc]; }
@end

i due file sopra sono le definizioni per un corretto parser xml.


Ma… come si usa?
Beh, è più facile di quanto sembra!

1
2
3
4
5
6
7
8
9
        /* dichiarazione e allocazione */
  ReverseGeo reverse = [ReverseGeo new];

  NSString *reverseUrl =
    [[NSString alloc] initWithString:@"http://sito.xml"];
  [reverse parseXMLFileAtURL:reverseUrl];
 
        /* accesso ai campi */
  NSLog(@"VIA: %@ - CITTA: %@", reverse->via, reverse->citta);

EOF!

[ref -> albertopasca.it]

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, ,

23
lug

A differenza di Java ed altri linguaggi, Objective-C non ha un metodo per convertire da decimale a binario e viceversa, o almeno… io non l’ho trovato!

Ecco qui:

Conversione da decimale a binario:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (NSString*) getBinary:(int)num {
  int m, no = 0, a = 1, rem;
 
  m = num;
  while(num != 0)
  {
    rem = num % 2;
    no  = no + rem * a;
    num = num / 2;
    a   = a * 10;
  }
  NSString *bin = [[NSString alloc] initWithFormat:@"%d", no];
  return bin;
}

Conversione da binario a decimale:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (NSString*) getDecimal:(NSString*)binary {
  int d = 0;
  NSString *a;
  for(int i=0; i< [binary length]; i++)
  {
    a = [[NSString alloc] initWithFormat:@"%c",
      [binary characterAtIndex:i]];
    double r = pow(2, [binary length] - 1 - i);
    d += ([a intValue] * r);
  }
  NSString *dec = [[NSString alloc] initWithFormat:@"%d", d];
  return dec;
}

è tutto!

[ref -> albertopasca.it]

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , ,

23
lug

Benvenuti nel blog degli appunti di viaggio!

Snipplets, funzioni interessanti, configurazioni di vario tipo, quasi tutto legato alla programmazione.

Iscriviti ai feed per essere sempre aggiornato sulle modifiche.

Avviso per gli utenti:
- i commenti verranno approvati prima della pubblicazione
- evitare lo spam o commenti inutili
- se si desidera commentare con codice usare la sintassi:

[cc lang= "lang" ] codice [/cc]

1
2
3
    private String funzione () {
        return "TEST";
    }

I linguaggi evidenziabili sono i seguenti:
abap, actionscript, actionscript3, ada, apache, applescript, apt_sources, asm, asp, autoit, avisynth, bash, basic4gl, bf, bibtex, blitzbasic, bnf, boo, c, c_mac, caddcl, cadlisp, cfdg, cfm, cil, cmake, cobol, cpp-qt, cpp, csharp, css, d, dcs, delphi, diff, div, dos, dot, eiffel, email, erlang, fo, fortran, freebasic, genero, gettext, glsl, gml, gnuplot, groovy, haskell, hq9plus, html4strict, idl, ini, inno, intercal, io, java, java5, javascript, kixtart, klonec, klonecpp, latex, lisp, locobasic, lolcode, lotusformulas, lotusscript, lscript, lsl2, lua, m68k, make, matlab, mirc, modula3, mpasm, mxml, mysql, nsis, oberon2, objc, ocaml-brief, ocaml, oobas, oracle11, oracle8, pascal, per, perl, php-brief, php, pic16, pixelbender, plsql, povray, powershell, progress, prolog, properties, providex, python, qbasic, rails, rebol, reg, robots, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, sql, tcl, teraterm, text, thinbasic, tsql, typoscript, vb, vbnet, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, whois, winbatch, xml, xorg_conf, xpp, yaml, z80

albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , ,

Switch to our mobile site