I am a newbie. Can anyone help me?
I have made a function with a programmable input field. I want to call this function several times and display the results at different coordinates on the screen.
What do I wrong and how should I solve it?
// inputName function
NSString* inputName (
int controlX,
int ControlY,
int controlWidth,
int controlHeight,
NSString* myQuestion)
{
// *********************** Inputfield **********************
UITextField *inlogName=[[UITextField alloc] initWithFrame:CGRectMake(controlX,controlY,controlWidth, controlHeight)];
[inlogName setBorderStyle:UITextBorderStyleRoundedRect];
[inlogName setPlaceholder: myQuestion];
[inlogName setDelegate:self]; // HERE I GET AN ERROR ???????
[inlogName text];
NSString *anwser= #"This is a dummy anwser";
[self.view addSubview:inlogName]; // HERE I GET ALSO AN ERROR ??????
return anwser;
}
You have created a C function and have no reference to self in it. I would suggest making it a method on your view controller and invoke it from there.
Related
I am trying to have multiple players for a card matching game. I have made a class that is a child of NSObject called Player. A Player object will have a name, high score, last score, and boolean is currently playing instance. I am trying to create a new player every time a new name is entered into a text field. I will work on storing the players later. Right now I just wish to make a new Player, have a user enter their name in the text field. And store the user's response in the text field. The following is my Player.m file
#import "Player.h"
#implementation Player
-(NSString *) nameOfPlayer:(Player *)playerName{
return self.name;
}
-(void) setPlayerName:(NSString *) nameOf{
self.name = nameOf;
self.lastScore = 0;
self.highestScore = 0;
self.playing = YES;
return;
}
-(id)init{
self = [super init];
self.name = #"";
self.lastScore = 0;
self.highestScore = 0;
self.playing = YES;
return self;
}
#end
I didn't originally have that init until I tried looking for a solution online. I am a bit new to iOS coding so I wasn't sure how to set up a constructor (or if they even have those). Below is how I tried to instantiate a Player object:
- (IBAction)handleButtonClick:(UIButton *)sender {
Player * friend = nil;
nameText = self.nameEntryField.text;
[friend setPlayerName:nameText];
NSLog(#"%#", [friend nameOfPlayer:friend]);
}
My app breaks its thread as soon as I try to setPlayerName. I am a bit stuck on this so any help would be appreciated.
- (IBAction)handleButtonClick:(UIButton *)sender {
Player * friend = [[Player alloc] init]; // Initialize this
nameText = self.nameEntryField.text;
[friend setPlayerName:nameText];
NSLog(#"%#", [friend nameOfPlayer:friend]);
}
You have done like Player * friend = nil; mean this is the nil object. And then you are trying to use method setPlayerName:on nil object. Because of this app breaks.
So you need to initialize object using [[Player alloc] init].
This is embarassing. I was unfamiliar with the xCode IDE and accidentally had selected that line of code for a breakpoint. The code is fine after previous answer.
I'm trying to use an UIActivityViewController with one long NSString as the data. If I put a string > 140 characters, the tweet sheet in it does not display the string. And if I truncate the string before giving it to the controller, all of the UIActivities have the truncated string. I don't want Facebook or Message to be truncated.
Is there a way to give different strings to different UIActivities?
Thank you!
(e.g. Marco Arment's The Magazine app does this by having a truncated string followed by #TheMagazineApp in UIActivityPostToTwitter, and other stuff in other UIActivities.)
I think this is what you're looking for: Custom UIActivityViewController icons and text.
You should be able to provide different data for each activity type.
Hope this helps somebody. It's pretty straightforward if you subclass UIActivityItemProvider:
#interface MyActivityItemProvider : UIActivityItemProvider
#end
#implementation MyActivityItemProvider
- (id)item
{
// Return nil, if you don't want this provider to apply
// to a particular activity type (say, if you provide
// print data as a separate item for UIActivityViewController).
if ([self.activityType isEqualToString:UIActivityTypePrint])
return nil;
// The data you passed while initialising your provider
// is in placeholderItem now.
if ([self.activityType isEqualToString:UIActivityTypeMail] ||
[self.activityType isEqualToString:UIActivityTypeCopyToPasteboard])
{
return self.placeholderItem;
}
// Return something else for other activities. Obviously,
// you can as well reuse the data in placeholderItem here.
return #"Something else";
}
#end
Then pass its instance with an array of activity items to UIActivityViewController:
MyActivityItemProvider *activityItem =
[[MyActivityItemProvider alloc] initWithPlaceholderItem:#"Your data"];
NSArray *sharingItems = [NSArray arrayWithObjects:
activityItem, _myUITextView.viewPrintFormatter, nil];
UIActivityViewController *activityController =
[[UIActivityViewController alloc]
initWithActivityItems:sharingItems applicationActivities:nil];
This can be easily done by using the optional activityType property from the UIActivityItemProvider object. That property returns a UIActivityType, so you can do something like:
class PhotoActivityItemProvider: UIActivityItemProvider {
...
override var item: Any {
guard let activityType = self.activityType else {
return photoURL.absoluteString
}
if activityType == .mail || activityType == .message {
return "The photo link is \(photoURL.absoluteString)."
}
...
}
More information in my blog post: https://www.whitesmith.co/blog/control-what-youre-sharing/
You can create a class that conforms to UIActivityItemSource and then pass its instance with an array of activity items to UIActivityViewController:, as #Mu-Sonic suggested.
If you want to know in which platform is the user sharing and return any specific data dependent on the tapped platform, override public func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any?
I was trying to work out how to read a text file stored on a web server and display the contents in a text view. I have followed the documentation from Apple website NSURLConnection of how to establish a NSURLConnection and receiveData and display the received data.
I have created a button where I want to load the text view on button click. For that I wrote this method
- (void)loadWeb:(BOOL)animated
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://nowayweb.com/mytext.txt"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (myConnection) {
downloadedData = [[NSMutableData data] retain];
}
else{
NSLog(#"Error");
}
}
But I am getting a warning in my .m file which can be seen in the screenshot as shown here:
It works fine and I can view the text in the text view, but I am wondering where am I making the mistake. If somebody throws some light on this, would be helpful.
Or is there a better way to load the contents from web by button click. Any help is appreciated.
Thanks
self is a pointer to an object, not a BOOL value. You should do this:
[self loadWeb: YES];
Except your method does not seem to use the parameter anyway, so you might as well get rid of it.
[self loadWeb];
and
- (void)loadWeb
{
// all the stuff inside
}
The reason it worked for you is a) you weren't using the parameter, b) the compiler will automatically convert self into a BOOL by chopping off all but the least significant byte of the pointer. If you had been using the parameter, most of the time it would have been YES by chance and occasionally it would have been NO by chance.
ObjC's BOOL is not a real boolean type. it is a typedef for a signed char.
The method's signature is:
- (void)loadWeb:(BOOL)animated
the expression [self loadWeb:self]; doesn't make sense, and it's not a real bool conversion. the compiler warns you that you are converting a pointer to a signed char.
It should read either:
[self loadWeb:YES];
-or-
[self loadWeb:NO];
-or-
BOOL someBOOLVariableOrParameter = ...; // YES or NO
[self loadWeb:someBOOLVariableOrParameter];
I have an NSTableView that lists tags that are stored using Core Data. The default value for a tag is 'untitled' and I need each tag to be unique, so I have a validation routine that traps empty and non-unique values and that works fine. I don't want the user to be able to store the 'untitled' value for a tag, so I am observing the NSControlTextDidEndEditingNotification, which calls the following code:
- (void)textEndedEditing:(NSNotification *)note {
NSString *enteredName = [[[note userInfo] valueForKey:#"NSFieldEditor"] string];
if ([enteredName isEqualToString:defaultTagName]) {
NSString *dString = [NSString stringWithFormat:#"Rejected - Name cannot be default value of '%#'", defaultTagName];
NSString *errDescription = NSLocalizedStringFromTable( dString, #"Tag", #"validation: default name error");
NSString *errRecoverySuggestion = NSLocalizedStringFromTable(#"Make sure you enter a unique value for the new tag.", #"Tag", #"validation: default name error suggestion");
int errCode = TAG_NAME_DEFAULT_VALUE_ERROR_CODE;
NSArray *objArray = [NSArray arrayWithObjects:errDescription, errRecoverySuggestion, nil];
NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey, NSLocalizedRecoverySuggestionErrorKey, nil];
NSDictionary *eDict = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray];
NSError *error = [[NSError alloc] initWithDomain:TAG_ERROR_DOMAIN code:errCode userInfo:eDict];
NSBeep();
[preferencesWindowsController presentError:error];
unsigned long index = [self rowWithDefaultTag];
[self selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];
// [self editColumn:0 row:index withEvent:nil select:YES];
}
}
- (unsigned long)rowWithDefaultTag {
__block unsigned long returnInt;
[managedTags enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj valueForKey:#"name"] isEqualToString:defaultTagName]) {
returnInt = idx;
*stop = YES;
}
}];
return returnInt;
}
With the 'editColumn' line commented out, the code works, so if the user accepts the default tag name without editing it, the error is built, displayed and the process finishes by leaving the appropriate row in the table highlighted.
However, I would like to take it that step further and place the user in edit mode. When I uncomment the 'editColumn' line, the behaviour is not at all what I expected - the tableView loses its blue focus box and the row that respresents the new tag is blank. If I click on the tableView, the row becomes visible. I've spent a lot of time on this and have got nowhere, so some help with this would be very much appreciated.
(Note: I tried using textDidEndEditing, which also didn't behave as I expected, but that is a separate issue!)
Answering my own question. Doh!
I already had a method which I used to put the user in edit mode when they clicked the button to add a new tag:
- (void)objectAdded:(NSNotification *)note {
if ([[note object] isEqual:self]) {
[self editColumn:0 row:[self rowWithDefaultTag] withEvent:nil select:YES];
}
}
Creating a notification to call this solves the problem and places the user in edit mode correctly. The important thing is not to try to do this on the existing runloop; so sending the notification as follows postpones delivery until a later runloop:
// OBJECTADDED is a previously defined constant.
NSNotification * note = [NSNotification notificationWithName:OBJECTADDED object:self];
[[NSNotificationQueue defaultQueue] enqueueNotification: note postingStyle: NSPostWhenIdle];
Problem solved. I wasted a lot of time trying to solve this - a classic example of getting too involved in the code and not looking at what I'm trying to do.
I've forgotten where I first saw this posted - whoever you are, thank you!
My tableview is get XML data from URL,First I declare a NSMutableArray *dataArray;
and this is how I get the data in my TableviewSample.m
- (void)getDataFromURL{
NSString *theURLAsString = [NSString stringWithFormat:GetAllData];//<-EXE_BAD_ACCESS HERE
//#define stringWithFormat:GetAllData #"http://192.168.10.28/req_alldata.php"
NSURL *theURL = [NSURL URLWithString:theURLAsString];
self.dataArray = [NSMutableArray arrayWithContentsOfURL:theURL];
}
Then I just get the elements form this array to my tableview ...
But here I have to say one more thing , actually it won't crash before I add another view...
I add a bar button to go to a webView , this webView is use to load a IP Cam stream video
When I back to the tableview , It will appear EXC_BAD_ACCESS
This is odd things I cannot to solve it...because both side code are all looks normal
If I remove this webview ,no matter how I run the program ,it won't crash...
And sometimes I leave the webView I will receive memory warning :level 2
But just only one time.
or do I use a wrong way to open an ip cam stream ???
Thanks for all reply : )
OK,here is the code different I use in my webview class
This is first version I use
- (void)viewDidAppear:(BOOL)animated{
NSString *directGoToWebCam = [NSString stringWithFormat:GetAllData];
self.IPCamWebView=[[[UIWebView alloc] initWithFrame:CGRectMake(0,0,640,960)] autorelease];
[self.IPCamWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:directGoToWebCam]]];
[self.view addSubview:self.IPCamWebView];
}
Where does GetAllData come from? It looks like that isn't pointing to anything. More code, the exact error, and a more careful description will go a long way here.
It probably has something to do with the use of #define which does not say anything about the type of the object you are using.
If you want to define a constant string in your code the best would be to use something like this:
static NSString *GetAllData = #"192.168.10.28/req_alldata.php";
Where you need to use the string you can simply write:
NSString *GoToWebCam = [NSString stringWithString:GetAllData];