How to call category method in another class - ios

I have category class have method to encode the url. So how to use this method in another class. Thank in advance
NSString+EncodeURL.h
#import <Foundation/Foundation.h>
#interface NSString (EncodeURL)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding;
#end
NSString+EncodeURL.m
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)));
}
and in another class. How to convert urlString to a string using urlEncodeUsingEncoding in Category class
#import "WatchVideosViewController.h"
#import "CustomCell.h"
#import "ImageRequest.h"
#import "Constant.h"
#import "ImageCache.h"
#import "NSString+EncodeURL.h"
#interface WatchVideosViewController ()
#property (weak, nonatomic) IBOutlet UIImageView *imageBackground;
#end
#implementation WatchVideosViewController
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString * CellIndentifier = kCellName;
CustomCell *cell = (CustomCell*)[collectionView dequeueReusableCellWithReuseIdentifier:CellIndentifier forIndexPath:indexPath];
NSDictionary *dictVideo = [self.videoList objectAtIndex:indexPath.row];
//start indicator
[cell.indicator startAnimating];
//set title
NSString *titleVideo = [dictVideo objectForKey:kTitleKey];
[cell.myLabel setText:titleVideo];
// set image url
NSString *urlVideo = [dictVideo objectForKey:kUrlKey];
NSURL *url = [NSURL URLWithString:urlVideo];
NSString *urlString = [url absoluteString];
NSString *encodeURL=[urlString ]
//encode url

In the file you want to make use of -urlEncodeUsingEncoding:, simply add:
#import "NSString+EncodeURL.h"
All NSString instances in that file will respond to -urlEncodeUsingEncoding:.

import "NSString+EncodeURL.h"
in the class u want to run NSString+EncodeURL.h--this class's method
Now u got to select where u got to run the method of (NSString+EncodeURL.h) this class.
suppose u want it to run in viewDidLoad,so
Create an instance of the class in the method.
NSString+EncodeURL *myInstance;
[myInstance methodname];

In the class where you want to use the category method, just simply import the category header as below.
#import "NSString+EncodeURL.h"
Then, use the category method as below
NSString *encodeURL = [urlString urlEncodeUsingEncoding:urlString];
Thats it, Simple, Bingo!

Example with NSStringEncoding is NSUTF8StringEncoding. You can convert urlString to encodeURL by call:
NSString *encodeURL=[urlString urlEncodeUsingEncoding:NSUTF8StringEncoding];
function CFStringConvertNSStringEncodingToEncoding() will convert NSUTF8StringEncoding to kCFStringEncodingUTF8

As in your code if you want to encode the url just write
NSString *encodeURL=[urlString urlEncodeUsingEncoding:NSUTF8StringEncoding]; //whataver encoding you want just pass
If code completion is not showing than there may be problem with indexing just terminae xcode reopen clean and build.It should work.

Related

Xcode 6: Why this code doesn't compile now?

My code was compiling and running great until I upgraded to Xcode 6.
Definition shows a Warning : Auto property synthesis will not synthesize property 'hash' because it is 'readwrite' but it will be synthesized 'readonly' via another property
#property (nonatomic, strong) NSString *hash; // (get/compute) hash code of the place (master hash of images)
Implementation shows error whenever I access to _hash: Use of undeclared identifier '_hash'
-(NSString *)hash {
if (_hash) return _hash;
// If place id, take it as the hash code
NSString *poiID = self.info[#"id"];
if (poiID) {
_hash = [NSString stringWithFormat:#"id-%lu",(unsigned long)[self.address hash]];
}
else if (CLLocationCoordinate2DIsValid(self.location.coordinate)) {
NSString *seed = [NSString stringWithFormat:#"%f,%f", self.location.coordinate.latitude, self.location.coordinate.longitude];
_hash = [NSString stringWithFormat:#"location-%lu",(unsigned long)[seed hash]];
}
else if (self.address) {
NSString *seed = self.address;
_hash = [NSString stringWithFormat:#"address-%lu",(unsigned long)[seed hash]];
}
else {
_hash = #"POI-unknownIDLocationOrAddress";
}
return _hash;
}
It doesn't compile because hash is already part of NSObject:
See:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/index.html#//apple_ref/occ/intfm/NSObject/hash
You need to add the following line to auto generate the setter method:
#synthesize hash = _hash;
If you don't want a setter method and only want a read-only property:
#property (nonatomic, strong, readonly) NSString *hash;

convert NSString into NSAttributedString without alloc init

I want to convert NSString into NSAttributedString.
But i always have to do
NSAttributedString *useDict1=[[NSAttributedString alloc] initWithString:#"String"];
Is there any other way such that i don't have to allocate the Dictionary every time, but just give the string?
I'd suggest to create a category on NSString with a method that converts it to NSAttributedString and then use that helper method across your project.
Like this:
#interface NSString (AttributedStringCreation)
- (NSAttributedString *)attributedString;
#end
#implementation NSString (AttributedStringCreation)
- (NSAttributedString *)attributedString {
return [[NSAttributedString alloc] initWithString:self];
}
#end

How to Save a NSString in a button?

I have opened gallery on a BUTTON click and choose an image.I save image full path
in a string.Now How can i save that string in button.I have to save string into a button so that button can hold the path.I have so many buttons like same in my view.and have to perform the same.The code I have used for saving Image path is written below.
// Get the image from the result
UIImage* image = [info valueForKey:#"UIImagePickerControllerOriginalImage"];
// Get the data for the image as a PNG
NSData* imageData = UIImagePNGRepresentation(image);
// Give a name to the file
NSString * imageName = #"Myimage.png";
// Now, we have to find the documents directory so we can save it
// Note that you might want to save it elsewhere, like the cache directory,
// or something similar.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// Now we get the full path to the file
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
// and then we write it out
[imageData writeToFile:fullPathToFile atomically:NO];
Button = fullPathToFile; ///This is the button
return;
Here the solution to add property to an object like UIButton etc.
UIButton+String.h
#import <Foundation/Foundation.h>
#interface UIButton (String)
#property (nonatomic, retain) NSString *path;
#end
UIButton+String.m
#import "UIButton+String.h"
#import <objc/runtime.h>
#implementation UIButton (String)
static char UIB_PROPERTY_KEY;
#dynamic path;
-(void)setPath:(NSDictionary *)attributes {
objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, path, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString *)path {
return (NSString*)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY);
}
#end
Create a model class, that is a class that has the necessary methods and properties to persist the data, add, delete and obtain the data. The model class can be a singleton to allow app wide access if necessary.
Views should just be used to display or to obtain user input.

Calling method from another file [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am a beginner in Objective-C. I would like to call the method two in file you.m from file me.m. Could you please teach me with simple example showing below to understand. Thank you!
you.h
#import <Foundation/Foundation.h>
#interface you : NSObject {
}
- (NSString *)one;
- (NSString *)two;
#end
you.m
#import "you.m"
#implementation you
- (NSString *)one {
NSString *a = #"this is a test.";
return a;
}
-(NSString *)two {
NSString *b = [self one];
return b;
}
#end
me.h
#import <Foundation/Foundation.h>
#interface me : NSObject {
}
#end
me.m
#import "you.h"
#import "me.h"
#implementation me
-(void)awakeFromNib{
//NSString *obj = [[[NSString alloc] init] autorelease];
//NSString *str = [obj two]; // dont work
//NSString *str = [self two]; // dont work
// I'd like to call method *two* from here.
NSLog(#"%#", str);
}
#end
In me class, create an instance of you.
you *objectYou=[you new];
As two returns a string, you need to store it :
NSString *string=[objectYou two];
In your code:
-(void)awakeFromNib{
you *objectYou=[you new];
NSString *str = [objectYou two];
NSLog(#"%#", str);
}
NOTE: Follow naming conventions. Class names must start with Capital letter like Me, You.
EDIT:
As you are learning, I would like to add one more thing, as you are calling one from two. If one is not meant to be called outside you class. You can define it in .m and remove the declaration from .h.
Simple, create an instance of You class in Me class and call that member function. Like so -
you *youInstance = [[you alloc] init];
NSString *retStr = [youInstance two];
Btw, its a good practice to CamelCase class names.
Also note this -
#interface you
- (NSString *) twoInstanceMethod;
+ (NSString *) twoClassMethod;
#end
NSString *retStr = [you twoClassMethod]; // This is ok
NSString *retStr = [you twoInstanceMethod]; // this doenst't work, you need an instance:
//so we create instance.
you *youInstance = [[you alloc] init];
NSString *retStr = [youInstance two];
Hope this clears some concepts...

iOS parser alloc breakpoint

.h
#class HtmlParser
#interface ClassName : NSObject <UITableViewDataSource>
{
NSString *img;
HtmlParser *htmlParser;
}
: )
.M
- (NSString*)img
{
if (img!=nil) return img;
if (_description!=nil)
{
// NSString* description = [NSString stringWithString:_description];
htmlParser = [[HtmlParser alloc] loadHtmlByString:(NSString*) _description];
}
return img;
}
I am trying to initialize HtmlParser with the contents of description. "description" is RSS html loaded asynchronously, started in the tableViewController.
I get a breakpoint with or without the NSString* description. '-[HtmlParser loadHtmlbyString:]: unrecognized selector sent to instance 0x75aa9b0'... That's all the debugging I know how to do. Breakpoints are enabled for all exceptions.
-the method in .m is called in the viewController's cellForRowAtIndexPath:
ClassName *object = _objects[indexPath.row];
NSString *i = object.img;
UIImage* iG = [UIImage imageWithData:
[NSData dataWithContentsOfURL:[NSURL URLWithString:i]]];
cell.imageView.image = iG;
Its messy so let me know if further clarification is needed.
.h
#interface HtmlParser: NSObject <NSXMLParserDelegate>
{
ET Cetera
}
- (id) loadHtmlByString:(NSString *)string;
When you call the method in question:
htmlParser = [[HtmlParser alloc] loadHtmlbyString:(NSString*) _description];
It shouldn't have the (NSString *) in there. It should be:
htmlParser = [[HtmlParser alloc] loadHtmlbyString: _description];
But, is loadHtmlbyString an init method? If so, then you should start the name with init, and you should also adhere to the naming conventions by capitalizing all the words in the name (including By).
The 'loadHtmlbyStringmethod is not a method of theHtmlParserclass, it is a method of yourClassName` class.
Don't you get a compiler warning on this line:
htmlParser = [[HtmlParser alloc] loadHtmlbyString:(NSString*) _description];
Look at the .h for the HtmlParser class and see what methods are defined for that class.

Resources